<template>
<div>
<h1>{{ greeting }}</h1>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
greeting: 'Hello',
message: 'Welcome to Vue 3 Single File Component!',
};
},
};
</script>
<style scoped>
/* 样式仅作用于当前组件 */
h1 {
color: blue;
}
p {
font-size: 16px;
}
</style>
在上述例子中,.vue 文件包含了三个部分:<template>、<script> 和 <style>。这三个部分分别定义了组件的模板、脚本和样式。
- <template>: 定义了组件的 HTML 模板。
- <script>: 包含了组件的脚本,导出一个对象,其中包含了组件的配置,如数据、生命周期钩子、方法等。
- <style>: 包含了组件的样式,scoped 属性表示样式只作用于当前组件。
要在你的应用中使用这个组件,只需在父组件中导入它:
<template>
<div>
<MyComponent />
</div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent,
},
};
</script>
确保你的项目配置了正确的构建工具(如 Vue CLI)来支持单文件组件的解析和编译。通常,使用 Vue CLI 创建的项目已经默认支持单文件组件。
转载请注明出处:http://www.zyzy.cn/article/detail/12990/Vue3