学习优先度:★★★★☆

难易度:★★★☆☆

Vue 3 中的设置函数是在创建组件之前执行的,因此它是初始化组件逻辑的首要位置。

设置函数是 Vue 3 中组件 API 的关键部分。它在任何组件生命周期钩子之前运行,允许你在组件生命周期的早期设置反应状态、计算属性和其他逻辑。

【代码示例】

<template>
  <div>{{ message }}</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
 setup() {
  // Define a reactive variable using ref
  const message = ref('Hello, Vue 3!');
  // Lifecycle hook to modify the message after the component is mounted
  onMounted(() => {
   message.value = 'Component is mounted!';
  });
  // Return the reactive variable to the template
  return {
   message
  };
 }
};
</script>

【执行结果】

textHello, Vue 3!
After the component is mounted, the message changes to:
textComponent is mounted!

setup 函数在创建组件之前被调用,因此它是初始化状态和设置逻辑的绝佳位置。ref 函数用于创建一个反应式变量,而 onMounted 则是一个生命周期钩子,在组件挂载后运行。这确保了任何依赖 DOM 的逻辑都能安全地执行。

【补充】

设置函数无法访问该对象,因为它是在创建组件实例之前调用的。相反,它会返回一个向模板公开属性和方法的对象。