9月20号vue.js子给父传值练习

2018-09-21  本文已影响0人  梁萌0328

效果图:


子给父传值实现对话效果案例.png

body部分:

<div id="itany">

   <my-father></my-father>
   
  </div>

js部分:

<script src="js/vue.js"></script>
<script>
  // 父组件
    Vue.component('my-father',{
        template:`
            <div>
                <ul>
                    <li v-for='(value,index) in chatcont'>{{value}}</li>
                </ul>
                <my-child @sendFather='rcvMsg' userName='Tom'></my-child>
                <my-child @sendFather='rcvMsg' userName='Jack'></my-child>
            </div>
        `, 
        data:function(){
            return{
                chatcont:[]
            }
        },
        methods:{
            rcvMsg:function(txt){
      // 给数组添加元素
                this.chatcont.push(txt)
            }
        }
      
       
    })
    //子组件
    Vue.component('my-child',{
        props:['userName'],
        template:`
            <div>
                <label>{{userName}}</label>
                <input type='text' v-model='msg'>
                <button @click='add'>发送</button>
            </div>
        `,
        data:function(){
            return{
                msg:''
            }
        },
        methods:{
            add:function(){
                this.$emit('sendFather',this.userName+':'+this.msg)
                this.msg=''
            }
        }
        
    })
    
    new Vue({
        el:"#itany"
    })
</script>
上一篇 下一篇

猜你喜欢

热点阅读