vue 组件间的传值 子传父

2018-09-22  本文已影响0人  闫梓璇

效果图:

未点击: QQ截图20180922094416.png
点击后: QQ截图20180922094509.png

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>
上一篇 下一篇

猜你喜欢

热点阅读