【vue3】三、data、computed、methods
简单数据ref复杂数据reactive使用方法:在useCount.js中引用ref、reactive导出useCount方法在useCount方法中定义data、methods,并return也没需要的data、methodsvue组件中引入useCount.jssetup中return导入的data、methodstemplate中使用data、methods// useCount.jsimp
·
简单数据ref
复杂数据reactive
使用方法:
- 创建文件useCount.js,
- 引用vue模块的ref、reactive、computed方法
- 自定义useCount方法,并导出
- 在useCount方法中定义data、methods、computed,并return组件中需要的data、methods、computed
- 组件中引入useCount.js
- setup中return导入的data、methods、computed
- template中使用data、methods、computed
// 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>
更多推荐
已为社区贡献1条内容
所有评论(0)