组件间的传值 子传父

点击前后对比图:


body:

 <div id="app">
   <my-father></my-father>
</div>

js:

<script>
      //父组件
      Vue.component('my-father',{
               template:
    `
        <div>
            <h1>{{mess}}</h1>
            <my-child v-on:send='Msg'></my-child>
        </div>
    `,
    data:function(){
        return{
            mess:''
        }
    },
    methods:{
        //父组件接收子组件传过来的值  值为txt
        Msg:function(txt){
            this.mess=txt
        }
    }
})
//子组件
Vue.component('my-child',{
    template:
    `
        <button @click='sendToFather'>传值给父元素</button>
    `,
    data:function(){
        return{
            message:'我是子组件,给父组件传值'
        }
    },
    methods:{
        sendToFather:function(){
            //         自定义事件,传输的数据
            this.$emit('send',this.message)
        }
    }
})

new Vue({
    el:'#app'
})
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容