vue组件父子组件通信

2018-09-23  本文已影响0人  张鑫冲
父子组件通信添加效果:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <div id='app'>
       <chat></chat>
   </div>
    <script src="../../js/vue.js"></script>
    <script>
    Vue.component('chat',{
        template:`
           <div>
              <ul>
                 <li v-for="value in arr">{{value}}</li>
              </ul> 
              <user @send='rcvMsg' userName='jack'></user>
              <user @send='rcvMsg' userName='rose'></user>
           </div>
       `,
        data:function(){
            return{
                arr:[]
            }
        },
        methods:{
            rcvMsg:function(txt){
                this.arr.push(txt)
            }
        }
    })  
    
    Vue.component('user',{
        props:['userName'],
        template:`
          <div>
             <label>{{userName}}</label>
             <input type='text' v-model='inputVal'>
             <button @click='sendMsg'>发送</button>
          </div>
        `,
        data:function(){
            return{
                inputVal:''
            }
        },
        methods:{
          sendMsg:function(){
              this.$emit('send',this.userName+':'+this.inputVal)
          }
        }
    }) 
    new Vue({
        el:'#app'
    })
    </script>
</body>
</html>

效果图:

QQ拼音截图未命名.png
上一篇下一篇

猜你喜欢

热点阅读