Vue3中的计算属性
今天继续更新关于Vue3中CompetitionApi关于计算属性的使用方法。在之前的OptionsApi中,计算属性这样写
const app = Vue.createApp({ data(){ return { ... } }, computed:{ computedData(){ ... } }, template:`<div>{{ computedData }}</div>` }) const vm = app.mount('#root')
下面举几个例子,结合代码中的注释说明一下。我们先针对基本数据类型,在CompetitionApi中,是这样的:
const app = Vue.createApp({ setup(){ const { ref,computed } = Vue // 从Vue中引入computed const count = ref(0) const handleClick = () => { count.value += 1 } const countAddFive = computed(() => { // 传递函数 return count.value + 5 }) return{ count, handleClick, countAddFive } }, template:`<div> <span @click="handleClick">{{ count }}</span>--- <span>{{ countAddFive }}</span> </div>` }) const vm = app.mount('#root')
我们除了可以传递函数 ,还可以更具体一点,传递对象,对象中包含了get和set,就像这样:
const app = Vue.createApp({ setup(){ const { ref,computed } = Vue const count = ref(0) const handleClick = () => { count.value += 1 } let countAddFive = computed({ get:() => { return count.value + 5 }, set:(v) => { // 接受传递来的参数 count.value = v } }) setTimeout(() => { // 返回的数据类型是基本数据类型,还是通过ref包裹的 countAddFive.value = 100 },3000) return{ count, handleClick, countAddFive } }, template:`<div> <span @click="handleClick">{{ count }}</span>--- <span>{{ countAddFive }}</span> </div>` }) const vm = app.mount('#root')
当然,除了基本数据类型,还有引用数据类型,下面以对象为例,代码可以写成这样:
const app = Vue.createApp({ setup(){ const { reactive,computed } = Vue const countObj = reactive({count:0}) const handleClick = () => { countObj.count += 1 } let countAddFive = computed({ get:() => { return countObj.count + 5 }, set:(v) => { // 接受传递来的参数 countObj.count = v } }) setTimeout(() => { // 返回的数据类型是基本数据类型,还是通过ref包裹的 countAddFive.value = 100 },3000) return{ countObj, handleClick, countAddFive } }, template:`<div> <span @click="handleClick">{{ countObj.count }}</span>--- <span>{{ countAddFive }}</span> </div>` }) const vm = app.mount('#root')
大家还可以扫描二维码,关注我的微信公众号,蜗牛全栈。