您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

vue父子组件通信使用方法

2024/3/11 9:31:44发布13次查看
这次给大家带来vue父子组件通信使用方法,使用vue父子组件通信的注意事项有哪些,下面就是实战案例,一起来看一下。
<!doctype html> <html>  <head>  <meta charset="utf-8">  <title>组件父子间通信之综合练习</title>  <script src="js/vue.js"></script>  </head>  <body>  <p id="container">   <p>{{msg}}</p>   <chat-room></chat-room>  </p>  <script> // 创建父组件   vue.component(chat-room,{   //data属性中的chatlist保存用户聊天信息    data:function(){     return{      chatlist:[]     }    },    template:`     <p>      //假的聊天室      <h1>假的聊天室</h1>      <user-component username="rose"></user-component>      <user-component username="jack"></user-component>      //显示用户的聊天信息      <ul>       <li v-for="tmp in chatlist">{{tmp}}</li>      </ul>     </p>    `   })  //创建子组件    vue.component(user-component,{    props:[username],    //通过v-model把用户输入的数据保存到userinput数组    data:function(){     return {      userinput:[]     }    },    methods:{     //把用户输入的数据以及用户名label信息push给chatlist数组     sendchat:function(){      this.$parent.chatlist.push(this.username+:+this.userinput);      //情况input框      this.userinput = ;     }    },    template:`     <p>      <label>{{username}}</label>      <input type="text" v-model="userinput"/>      <button @click="sendchat">发送</button>     </p>    `   })   new vue({    el:#container,    data:{     msg:hello vuejs    }   })  </script>  </body> </html>
组件间通信综合练习:
(props down,events up)
有2个组件:chat-room,user-component
user-component是由label input button构成
chat-room是由两个user-component和一个列表构成
①在chat-room调用user-component指定label的名字
②在user-component,
点击按钮时,将当前用户输入的信息发送给chat-room组件,chat-room接收到数据显示在列表中
代码:
<!doctype html> <html> <head lang="en">  <meta charset="utf-8">  <script src="js/vue.js"></script>  <title></title> </head> <body> <p id="container">  <chat-room></chat-room> </p> <script>  vue.component('chat-room',{   methods:{    recvmsg:function(msg){     console.log(在父组件中接收子组件传来的数据+msg);     this.chatlist.push(msg);    }   },  data: function () {   return {   chatlist:[]   }  },  template:`   <p>     <h1>假的聊天室</h1>   <ul>    <li v-for="tmp in chatlist">    {{tmp}}    </li>   </ul>   <user-component username="lucy" @sendtofather="recvmsg"></user-component>   <user-component username="merry" @sendtofather="recvmsg"></user-component>   </p>   `  })  vue.component('user-component',{  props:['username'],  data: function () {   return {   userinput:''   }  },  methods:{   sendtofather: function () {   //触发tofatherevent的事件,把input中   //用户输入的数据发送   this.$emit(sendtofather,this.username+:+this.userinput);   }  },  template:`   <p>   <label>{{username}}</label>   <input type="text" v-model="userinput"/>   <button @click="sendtofather">发送</button>   </p>   `  })  new vue({  el: '#container',   data: {   msg: 'hello vue'   }  }) </script> </body> </html>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
mint-ui loadmore上拉加载与下拉刷新冲突处理方法
在es6里模板字符串使用详解
以上就是vue父子组件通信使用方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product