美文网首页
2018-09-23

2018-09-23

作者: 慎独_AB | 来源:发表于2018-09-23 19:59 被阅读0次

vue组件的生命周期:

图解


QQ图片20180923195147.png

分为
创建前(beforeCreate)、已创建(created)、编译前(beforeMount)、编译后(mounted)、更新前(beforeUpdate)、更新后(update)、销毁前(beforeDestroy)、销毁后(destroyed)几个阶段

举例使用生命周期进行非父子直接的传值:

  <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'
   })
   
  //       v-HTML
  //       v-text
  //       v-cloak
    </script>

还有就是在实例中最后使用的箭头函数:

在这个地方需要使用箭头函数,因为如果在这里使用平时使用的this的话会指向整个vue实例而不是这个组件
箭头函数在这里可以指向这个组件箭头函数在哪个组件内使用就指向哪个组件。

相关文章

网友评论

      本文标题:2018-09-23

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