温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue.js中兄弟组件之间互相传值实例

发布时间:2020-10-14 23:44:05 来源:脚本之家 阅读:161 作者:小码过河找八哥 栏目:web开发

兄弟组件之间互相传值,需要建立一个“中转站”(新的vue实例),并且需要主动触发。

实例上的$on方法来接受监听。

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>组件传值</title>
 <script src="vue.js"></script>
</head>
<body>
 <div id="box">
 <child1></child1>
 <child2></child2>
 </div>

 <template id="c1">
 <h2>~~~~~~我是哥哥~~~~{{msg}} <button @click='fn'>点击</button></h2>
 </template>
 <template id="c2">
 <h4>~~~~~~我是弟弟~~~~{{msg2}}</h4>
 </template>
</body>
</html>
<script>
 var Hub=new Vue();  // 1) 中转站,其中不需要设置任何参数

 var vm=new Vue({
 el: '#box',
 components:{
  child1:{
  template:'#c1',
  data:function(){
   return {
   msg: 'hello'
   }
  },
  methods:{
   fn:function(){
   // 2) 主动触发监听(中转站触发监听)
   console.log(this.msg); //hello
   Hub.$emit('change',this.msg) //$emit触发监听方法
   }
  }
  },
  child2:{
  template:'#c2',
  data:function(){
   return {
   msg2: 'world'
   }
  },
  // 创建完成  new Vue  create mount
  // 钩子函数
  created(){
   // 3) 接收监听  $on('事件名称',function(val){}) val是传递过来的值
   Hub.$on('change',function(val){
   console.log(val) //hello
   // this.msg2 = val;
   })
  }
  }
  
 }
 })
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI