文章目錄
- 前言
- 一、單文件組件的構成
- 二、組件引用
- 三、組件的應用舉例
- 1.組件實例
- 2.顯示結果
前言
Vue 單文件組件(又名 *.vue
文件,縮寫為 SFC)是一種特殊的文件格式,它允許將 Vue 組件的模板、邏輯 與 樣式封裝在單個文件中。組件最大的優勢就是可復用性
一、單文件組件的構成
vue組件基本包括以下幾個方面:
- 模板頁面
- js模塊
- 樣式
<!--模板 -->
<template><h3>單文件組件</h3>
</template>
<!--js模塊 -->
<script>
export default {name:"MyComponent"
}
</script>
<!--樣式 -->
<style scoped>
h3{color: red;
}
</style>
二、組件引用
第一步:導入組件 import MyComponentVue from ./components/MyComponent.vue'
第二步:注冊組件 components: { MyComponentVue }
第三步:引用組件標簽 <MyComponentVue />
三、組件的應用舉例
1.組件實例
定義兩個組件 schoo.vue和student.vue
school.vue
<template><!-- 組件的結果 --><div class="demo"><h2>學校名稱:{{name}}</h2><h2>學校地址:{{address}}</h2><button @click="showName">點我提示學校名</button> </div>
</template><script>//組件的交互export default {name:'School',data(){return {name:'vue學院',address:'上海黃浦區'}},methods: {showName(){alert(this.name)}},}
</script><!-- 組件的樣式 -->
<style>.demo{background-color: orange;}
</style>
student.vue
<template><div><h2>學生姓名:{{name}}</h2><h2>學生年齡:{{age}}</h2></div>
</template><script>export default {name:'Student',data(){return {name:'張三',age:18}}}
</script>
在根組件App.vue 組件中,
①導入import組件
②注冊組件
③引用組件標簽
App.vue
<template><div><!-- 引用組件標簽 --><School></School><Student></Student></div>
</template><script>// 導入組件import School from './School.vue'import Student from './Student.vue'export default {name:'App',// 注冊組件components:{School,Student}}
</script>