在 setup 中声明函数共有 4 种方式:直接声明函数使用 vue.reactive 创建可变响应式对象使用 vue.computed 创建计算属性使用 vue.watch 创建侦听器
Vue 中在 setup 中声明函数
在 Vue 3.0 中,setup 函数提供了声明响应式状态、计算属性和方法的新方式。以下是如何在 setup 中声明函数:
直接声明函数
import { defineProps } from '<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15721.html" target="_blank">vue</a>'
export default {
props: defineProps(['count']),
setup() {
function incrementCount() {
// ...
}
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}
使用Vue.reactive创建可变响应式对象
import { defineProps, reactive } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const state = reactive({
count: 0,
increment: function() {
// ...
}
})
// 其他逻辑...
return {
// ...其他响应式状态
...state
}
}
}
使用Vue.computed创建计算属性
import { defineProps, computed } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const incrementCount = computed(() => {
// ...
})
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}
使用Vue.watch创建侦听器
import { defineProps, watch } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const incrementCount = watch('count', (newValue, oldValue) => {
// ...
})
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}
通过这些方法,可以在 Vue 3.0 的 setup 函数中以响应式的方式声明函数。