学习优先度:★★★★★
难易度:★★★★☆
Vue 的 Composition API 中的 setup 函数用于声明反应状态和其他逻辑,从而使代码的组织和重用变得更加容易。
下面的示例展示了如何在设置函数中声明反应状态。
【代码示例】
import { ref } from 'vue';
export default {
setup() {
// Declare reactive state variables
const message = ref('Hello, Vue 3!');
const count = ref(0);
// Function to update the message
const updateMessage = () => {
message.value = 'Hello, Composition API!';
};
// Function to increment the count
const increment = () => {
count.value++;
};
return {
message,
count,
updateMessage,
increment
};
}
};
【执行结果】
textmessage: 'Hello, Vue 3!'
count: 0
// After calling updateMessage()
message: 'Hello, Composition API!'
// After calling increment()
count: 1
在本例中,使用 ref 创建了反应状态变量 message 和 count。设置函数返回这些变量和更新它们的函数,使它们可以在模板中访问。当 updateMessage 或 increment 被调用时,反应状态就会更新,变化也会反映在模板中。
【补充】
设置函数是在 Vue 组件中使用 Composition API 的入口点。通过它,您可以按逻辑关注点组织代码,使组件更具可读性和可维护性。ref 函数为一个值创建一个反应式引用,可用于模板或其他反应式函数。