Vue 向组件中插入内容

 

向组件中插入内容有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部分的实例

 

posted @ 2020-04-01 17:35  chy_18883701161  阅读(4360)  评论(0编辑  收藏  举报