向組件中插入內容有2種方式
- 槽點
- 子組件
demo 使用槽點向組件中插入內容
Vue.component('Parent',{
template:` <!--反引號比引號更好用-->
<div>
<p>hello</p>
<slot></slot> <!--如果后續要在組件中插入元素、內容,需要先留好槽點,不能直接插入-->
</div>
`
})
new Vue({
el:'#app',
template:`
<div>
<parent> <!--使用parent組件-->
<p>I am chy </p> <!--使用組件時,組件標簽的innerHtml會作為一個整體,替換槽點-->
<p>nice to meet you</p> <!--必須要有槽點,不然innerHtml不知道放哪兒,無效-->
</parent>
</div>
`
});
槽點未設定name時,使用該組件標簽時,整個innerHtml都會被插入到槽點,slot是動態dom,innerHtml有多少內容,就插入多少內容,
如果不設定槽點,2個<p>元素不能插入到組件中,
demo 槽點設定name
Vue.component('Parent',{
template:`
<div>
<p>hello</p>
<slot name="info"></slot> <!--槽點設定了name-->
</div>
`
})
new Vue({
el:'#app',
template:`
<div>
<parent> <!--使用parent組件-->
<p slot="info">I am chy </p> <!--如果槽點設定了name,必須指定要插入的槽點-->
<p>nice to meet you</p> <!--這個沒有指定槽點,無效-->
</parent>
</div>
`
});
demo 父子組件
Vue.component('Child',{
template:`
<div>
<p>I am chy</p>
<p>nice to meet you</p>
</div>
`
})
Vue.component('Parent',{
template:`
<div>
<p>hello</p>
<child></child> <!--子組件-->
</div>
`
})
new Vue({
el:'#app',
template:`
<div>
<parent></parent>
</div>
`
});
demo 獲取父|子組件物件
//子組件 Vue.component('Child',{ template:` <div> <p>I am chy</p> <p>nice to meet you</p> </div> `, data(){ return { msg:'this is the child' } }, mounted() { //生命周期方法,dom加載完成 console.log(this.$parent); //訪問父組件物件|實體 } }) // 父組件 Vue.component('Parent',{ template:` <div> <p>hello</p> <child ref="son"></child> <!-- ref給子組件的參考起一個名字 --> </div> `, data(){ return { msg:'this is the parent' } }, mounted() { console.log(this.$refs.son); //訪問子組件物件|實體:this.$refs.子組件的ref屬性值 } }) new Vue({ el:'#app', template:` <div> <parent></parent> </div> ` });
只要當前dom中有元素使用了ref屬性,就可以使用 this.$refs.ref屬性值 來獲取對應的實體
常用的還有
- this.$el 獲取el對應元素的dom
- this.$data 獲取data部分的實體
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/137749.html
標籤:JavaScript
上一篇:Vue 組件開發
