data、computed、methods 拆分使用

// useCount.js
import {ref,reactive,computed} from 'vue'

export default function useCount() {
    // 简单数据定义及使用
    let count = ref(0)
    function addCount() {
        count.value++
    }

    // 复杂数据定义级修改
    let count_obj = reactive({
        val:10
    })
    let changeCountObj = ()=> {
        count_obj.val = count.value;
    }

    // 计算变量
    let count_dobule = computed(()=>{
        return count.value*2
    })
    return {count, addCount,count_obj, changeCountObj,count_dobule}
}

 

// Home.vue
<template>
    <div>
        <button @click="addCount">count is {{count}}</button>
        <button @click="changeCountObj">点击同步count值:{{count_obj.val}}</button>
        <div>count的两倍是:{{count_dobule}}</div>
    </div>
</template>

<script>
    import useCount from "./useCount";
    export default {
        setup() {
            let {count, addCount,count_obj,changeCountObj,count_dobule} = useCount();
            return {
                count, addCount,count_obj,changeCountObj,count_dobule
            }
        }
    }
</script>

 

上一篇:vue(31)vue中CompositionAPI组合API的使用


下一篇:vue中点击显示更多/隐藏