setup返回的对象数据如果想被模版正确解析,必须是一个ref函数返回的类型
<template>
<div>
<h1>{{ count }}</h1>
<div>{{double}}</div>
<button @click="increase">add</button>
</div>
</template>
<script lang="ts">
import { ref, computed } from 'vue'
export default {
name: 'HelloWorld',
setup () {
const count = ref(0)
const double = computed(() => {
return count.value * 2
})
const increase = () => {
count.value++
}
return {
count,
increase,
double
}
}
}
</script>
但此时会发现代码写起来很麻烦
<template>
<div>
<h1>{{ count }}</h1>
<div>{{double}}</div>
<button @click="increase">add</button>
</div>
</template>
<script lang="ts">
import { computed, reactive, toRefs } from 'vue'
export default {
name: 'HelloWorld',
setup () {
const data = reactive({
count: 0,
increase: () => {
data.count++
},
double: computed(() => { return data.count * 2})
})
const refData = toRefs(data)
return {
...refData
}
}
}
</script>
网友评论