美文网首页
非父子传值

非父子传值

作者: 苏凉_169e | 来源:发表于2018-09-23 19:23 被阅读0次

1,生命周期
在vue一整个的生命周期中会有很多钩子函数提供给我们在vue生命周期不同的时刻进行操作:

   // beforeCreate
   // created
   // beforeMount
   // mounted
   // beforeUpdate
   // updated
   // beforeDestroy
   // destroyed

2,同级传值

(1):新建一个空的root组件:let Event=new Vue();
(2):发送数据的组件:Event.$emit('a-fnName',data) 写在组件的methods里

(3):接收数据的组件:Event.$on('a-fnName',(data)=>{}),注意函数格式必须写为箭头函数,不然this指向不是当前组件

两个独立的组件不能进行传输,需要借助第三方量;
在组件模板中不能同时存在两个以上的兄弟元素,需用一个div包起来;
在全局组件中,必须把组件放在new Vue() 的上面,否则会报错
例:

<div id='app'>
     <child></child>
     <son></son>
</div>
<script src='js/vue.js'></script>
<script>
   var bus=new Vue();
   Vue.component('child',{//A
       template:`
        <div>
           <h1>我是child组件</h1>
           <button @click='sendMsg'>发送数据给son</button>
        </div>
       `,
       data:function(){
           return{
               msg:'hello vue'
           }
       },
       methods:{
           sendMsg:function(){
              bus.$emit('send',this.msg) 
           }
       }
   }) 
   Vue.component('son',{//B
       template:`
        <div>
           <h1>我是son组件</h1>
           <a href=''>{{mess}}</a>
        </div>
       `,
       data:function(){
           return{
               mess:''
           }
       },
       mounted:function(){
           bus.$on('send',msg=>{//箭头函数
               console.log(this);
               this.mess=msg
           })
       }
   }) 
   new Vue({
       el:'#app'
   })

相关文章

网友评论

      本文标题:非父子传值

      本文链接:https://www.haomeiwen.com/subject/hnjqoftx.html