美文网首页
组件间传值案例 两人对话

组件间传值案例 两人对话

作者: 辞苏 | 来源:发表于2018-09-23 19:22 被阅读0次
body:

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

js:

<script>
Vue.component('my-father',{
    template:
    `       <div>
                <ul>
                    <li v-for='(value,index) in arrs'>{{value}}</li>
                </ul>
                <my-child @send='sent' userName='jack'></my-child>
                <my-child @send='sent' userName='rosc'></my-child>
            </div>
    `,
    data:function(){
        return{
            arrs:[]
        }
    },
    methods:{
        sent:function(text){
            this.arrs.push(text)
        }
    }
})

Vue.component('my-child',{
    props:['userName'],
    template:
    `
        <div>
            <span>{{userName}}</span>
            <input type='text' v-model='mess'><button @click='add'>添加</button>
        </div>
    `,
    data:function(){
        return{
            mess:''
        }
    },
    methods:{
        add:function(){
            this.$emit('send',this.userName+':'+this.mess)
        }
    }
})
new Vue({
    el:'#app'
})
</script>

相关文章

网友评论

      本文标题:组件间传值案例 两人对话

      本文链接:https://www.haomeiwen.com/subject/mceqoftx.html