天天看點

Vue 向元件中插入内容

向元件中插入内容有2種方式

  • 槽點
  • 子元件

demo  使用槽點向元件中插入内容

  Vue.component('Parent',{
        template:`  hello        `
    })    
        
    new Vue({
        el:'#app',
        template:`        I am chynice to meet you        `
    });      

槽點未設定name時,使用該元件标簽時,整個innerHtml都會被插入到槽點。slot是動态dom,innerHtml有多少内容,就插入多少内容。

如果不設定槽點,2個

元素不能插入到元件中。

demo   槽點設定name

  Vue.component('Parent',{
        template:`        hello        `
    })    
        
    new Vue({
        el:'#app',
        template:`        I am chynice to meet you        `
    });      

demo  父子元件

  Vue.component('Child',{
        template:`        I am chynice to meet you        `
    })

    Vue.component('Parent',{
        template:`        hello        `
    })    
        
    new Vue({
        el:'#app',
        template:`                `
    });      

demo  擷取父|子元件對象

  //子元件
    Vue.component('Child',{
        template:`        I am chynice to meet you        `,
        data(){            return {
                msg:'this is the child'
            }
        },
        mounted() {  //生命周期方法,dom加載完成
            console.log(this.$parent);  //通路父元件對象|執行個體        }
    })    // 父元件
    Vue.component('Parent',{
        template:`        hello        `,
        data(){            return {
                msg:'this is the parent'
            }
        },
        mounted() {
            console.log(this.$refs.son);  //通路子元件對象|執行個體:this.$refs.子元件的ref屬性值        }
    })    
        
    new Vue({
        el:'#app',
        template:`                `
    });      

隻要目前dom中有元素使用了ref屬性,就可以使用  this.$refs.ref屬性值  來擷取對應的執行個體

  • this.$el    擷取el對應元素的dom
  • this.$data   擷取data部分的執行個體