外观
组件基础
单文件组件
Vue 单文件组件(又名 *.vue 文件,缩写为 SFC)是一种特殊的文件格式,它允许将 Vue 组件的模板、逻辑 与 样式封装在单个文件中。
<template>
<h3>单文件组件</h3>
</template>
<script>
export default {
name:"MyComponent"
}
</script>
<style scoped>
h3{
color: red;
}
</style>style标签添加scoped属性指此文件内的CSS样式只在此组件内生效,因此它里面的选择器可以和其它组件内的选择器重复。
加载组件
第一步:引入组件 import MyComponentVue from './components/MyComponent.vue'
第二步:挂载组件 ,在export default中填写components: { MyComponentVue }
第三步:显示组件,在template中使用 <my-componentVue />
例:在components文件夹下创建MyComponent1.vue和MyComponent2.vue两个文件,然后更改App.vue内容:
<script setup>
import MyComponent1 from './components/MyComponent1.vue'
</script>
<template>
<MyComponent1 />
</template>MyComponent1.vue:
<script>
import MyComponent2 from "@/components/MyComponent2.vue"; // 导入子组件,组件名称一般与文件名相同
export default {
components: {
MyComponent2 // 子组件名称,与上方导入的一致
},
data() {
return {
msg: '这是自定义组件MyComponent1的msg内容'
}
}
}
</script>
<template>
<MyComponent2 /> // 然后就可以在这里使用components变量声明过的组建了
<p>{{ msg }}</p>
</template>
<style scoped>
</style>MyComponent2.vue:
<script>
export default {
data() {
return {
msg: `这个是MyComponent2组件内的msg变量`
}
},
}
</script>
<template>
<h2>这个是MyComponent2组件内的内容</h2>
{{ msg }}
</template>
<style scoped>
h2 {
color: red;
font-size: 20px;
}
</style>
<!--此组件由于没有引入任何组件,因此就像普通组件那样写就可以-->原理是在App.vue中指注册MyComponent1组件,然后在MyComponent1组件中注册MyComponent2组件,就达到了组件嵌套的效果。
组件的具体位置中,可以使用类似于大写字母开头的组件名称,如MyComponent,也可以使用连字符形式,如my-component。