要成功,就要长期等待而不焦躁,态度从容却保持敏锐,不怕挫折且充满希望。早安!减少蜗居时间,亲近大自然。
兄弟组件之间互相传值,需要建立一个“中转站”(新的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"> <h1>~~~~~~我是哥哥~~~~{{msg}} <button @click='fn'>点击</button></h1> </template> <template id="c2"> <h3>~~~~~~我是弟弟~~~~{{msg2}}</h3> </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>
以上就是Vue.javascript中兄弟组件之间互相传值实例。回首,留不住岁月。凝眸,牵不住时光。于是,咱们淡然微笑,释然。更多关于Vue.javascript中兄弟组件之间互相传值实例请关注haodaima.com其它相关文章!