Vue.js中使用components組件的實(shí)例講解
Vue.js使用components組件
組件(vue文件)的結(jié)構(gòu)
<!--頁面模板-->
<template>
? <div> {{msg}}</div>
</template>
<!--JS 模塊對(duì)象-->
<script>
? export default {
? ? data () {
? ? ? return {msg: 'vue模板頁'}
? ? }
? }
</script>
<!--css樣式-->
<style>
</style>組件的基本使用
- 引入組件
- 映射成標(biāo)簽
- 使用組件標(biāo)簽
<template>
? <!--3.使用組件標(biāo)簽-->
? <HelloWorld/>
</template>
<script>
? //1.引入組件
? import HelloWorld from './components/HelloWorld.vue'
? export default {
? ? //2.映射組件標(biāo)簽
? ? components: {
? ? ? HelloWorld
? ? }
? }
</script>vue定義組件 components(局部 / 全局)
基本信息
組件是對(duì)你 html 標(biāo)簽的一個(gè)拓展
組件里面的內(nèi)容就是你模板的內(nèi)容
組件分為全局組件和局部組件
對(duì)象當(dāng)中定義的組件都是局部組件
如何定義(注冊(cè))組件
- 定義組件需要使用components選項(xiàng)。components是一個(gè)對(duì)象,該對(duì)象的屬性是組件的相關(guān)配置信息。
- 組件當(dāng)中至少應(yīng)該擁有template屬性或render方法。
- 使用時(shí),可以將組件的名字作為標(biāo)簽來使用。
注意:
當(dāng)你的組件名稱當(dāng)中使用駝峰命名時(shí),在使用組件時(shí),名字小寫與大寫之間應(yīng)該用-來分割。
組件當(dāng)中的數(shù)據(jù),與其外部的實(shí)例是不共享的。
在組件內(nèi)定義的數(shù)據(jù)(data)
- 必須要是一個(gè)函數(shù)
- 函數(shù)必須要有返回值
- 返回值必須要是一個(gè)對(duì)象
局部組件
<Zujian></Zujian> ?// html 中可以使用已經(jīng)定義好的組件
new Vue({
?? ?el:"#root",
?? ?data:{
?? ?... ...
?? ?},
?? ?components:{ ? ? //可以看到 components 是復(fù)數(shù)形式,說明我們可以在這里面定義多個(gè)組件
?? ?Zujian:{ ? ? ? ? //定義了一個(gè)名字為 zujian 的組件 ?//它是一個(gè)對(duì)象形式
?? ??? ?template:`<div>定義了一個(gè)組件,名字為 zujian </div>` ? ?//組件具體內(nèi)容
?? ??? ?}
?? ?}
})全局組件
Vue.component('Zujian', { ? ?//在 new Vue 之外書寫 // script 中書寫
? template: `<div>定義了一個(gè)組件,名字為 zujian </div> `
})<Zujian></Zujian> ?// html 中可以使用已經(jīng)定義好的組件
引入外部組件
//引入外部組件
<script>
import Zujian from './components/zujian.js'
export default{
?? ?data(){
?? ??? ?return{
?? ??? ??? ?... ...
?? ??? ?}
?? ?},
?? ?components:{
?? ??? ?Zujian
?? ?}
}
</script>//外部組件 <template> ?? ?<div>hello world?。。?lt;/div> <template> <script> ?? ?... ... </script>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue.js實(shí)戰(zhàn)之使用Vuex + axios發(fā)送請(qǐng)求詳解
這篇文章主要給大家介紹了關(guān)于Vue.js使用Vuex與axios發(fā)送請(qǐng)求的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-04-04
詳解vue2如何實(shí)現(xiàn)點(diǎn)擊預(yù)覽本地文件
這篇文章主要為大家詳細(xì)介紹了vue2如何實(shí)現(xiàn)點(diǎn)擊預(yù)覽本地的word、excle、pdf文件,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
Vue實(shí)現(xiàn)數(shù)字時(shí)鐘效果
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)數(shù)字時(shí)鐘效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
vue解析Json數(shù)據(jù)獲取Json里面的多個(gè)id問題
這篇文章主要介紹了vue解析Json數(shù)據(jù)獲取Json里面的多個(gè)id問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12

