// Vue 3 组件中使用 created 生命周期钩子的示例代码
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
name: 'MyComponent',
setup() {
// 定义一个响应式变量
const message = ref('Hello, Vue 3!');
// 使用 created 钩子(在 setup 函数中直接编写逻辑)
// 在组件实例创建完成后立即执行
console.log('Component is created.');
// 返回需要在模板中使用的变量或函数
return {
message,
};
},
};
</script>
<style scoped>
/* 样式部分可以根据需要添加 */
</style>
模板部分 (<template>):
message 变量的内容。脚本部分 (<script>):
setup 函数) 来替代选项式 API。ref 用于创建一个响应式变量 message。setup 函数中直接编写逻辑,相当于 Vue 2 中的 created 钩子。这里的 console.log 语句会在组件实例创建完成后立即执行。message,使其可以在模板中使用。样式部分 (<style scoped>):
如果你希望使用选项式 API 的 created 钩子,可以参考以下代码:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
name: 'MyComponent',
data() {
return {
message: 'Hello, Vue 3!',
};
},
created() {
// 在组件实例创建完成后立即执行
console.log('Component is created.');
},
};
</script>
<style scoped>
/* 样式部分可以根据需要添加 */
</style>
data 函数来定义响应式数据 message。created 钩子,在组件实例创建完成后立即执行逻辑。console.log 语句会在组件实例创建完成后输出信息。这两种方式都可以实现类似的功能,选择哪种方式取决于你的项目需求和个人偏好。
上一篇:vue icon
下一篇:vue3 emit用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站