在 setup 中声明函数共有 4 种方式:直接声明函数使用 Vue.reactive 创建可变响应式对象使用 Vue.computed 创建计算属性使用 Vue.watch 创建侦听器

在 Vue 3.0 中,setup 函数提供了声明响应式状态、计算属性和方法的新方式。以下是如何在 setup 中声明函数:
直接声明函数
<code class="js">import { defineProps } from 'vue'
export default {
props: defineProps(['count']),
setup() {
function incrementCount() {
// ...
}
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}</code>使用Vue.reactive创建可变响应式对象
<code class="js">import { defineProps, reactive } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const state = reactive({
count: 0,
increment: function() {
// ...
}
})
// 其他逻辑...
return {
// ...其他响应式状态
...state
}
}
}</code>使用Vue.computed创建计算属性
立即学习“前端免费学习笔记(深入)”;
<code class="js">import { defineProps, computed } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const incrementCount = computed(() => {
// ...
})
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}</code>使用Vue.watch创建侦听器
<code class="js">import { defineProps, watch } from 'vue'
export default {
props: defineProps(['count']),
setup() {
const incrementCount = watch('count', (newValue, oldValue) => {
// ...
})
// 其他逻辑...
return {
// ...其他响应式状态
incrementCount
}
}
}</code>通过这些方法,可以在 Vue 3.0 的 setup 函数中以响应式的方式声明函数。
以上就是vue中setup怎么声明函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号