VUE2.0常见的钩子函数

2,778 阅读3分钟
var vm = new Vue({
	el: '#app',			// 生效范围
    data () {},			// 数据
    methods: {},		// 方法
    filter: {},			// 过滤器
    directives: {},		// 自定义指令(用的少)
    components: {},		// 载入组件
    // 生命周期函数,除了created、mounted以外别的很少用
    beforeCreate () {},
    created () {},
    beforeMount () {},
    mounted () {},
    beforeUpdate () {},
    updated () {},
    beforeDestroy () {},
    destroyed () ()
})

常用:beforeCreate、created、mounted、computed、watch

beforeCreate

这个时候,this变量还不能使用,在data下的数据、methods下的方法、watch中的事件都不能获得

 beforeCreate() {
   console.log(this.page); // undefined
   console.log{this.showPage); // undefined
 },
 data() {
   return {
     page: '第一页'
   }
 },
 methods: {
   showPage() {
     console.log(this.page);
   }
 }
created

这个时候可以操作vue实例中的数据和各种方法,但是还不能对DOM节点进行操作

created() {
    let btn = document.querySelector('button')
    console.log(btn.innerText)  //此时找不到button节点,打印不出来button的值
}
mounted

这个时候挂载完毕,这时dom节点被渲染到文档内,一些需要DOM的操作在此时才能正常进行

mounted() {
    let btn = document.querySelector('button')
    console.log(btn.innerText)  //此时可以打印出来button的值
}
computed

把所有需要依赖其它值计算的值写成对象的key值

  data() {
    return {
      count: 1
    }
  },
 computed: {
    //是最后需要计算的值,而这个值依赖this.count 
    //那么这个值要写在对象的key值的位置
    countDouble: {
      get: function() {
        return this.count * 2
      },
      set: function(newValue) {
        this.countDouble = newValue
      }
    }   
  }
watch

把监听的值写成对象的key值

 data() {
    return {
      count: 1
    }
  },
  watch: {
    count: (val, oldVal) => {
      console.log('new: %s, old: %s', val, oldVal)
    }
  }

这时如果this.count发生了改变,那么监听count变量发生变化的funtion就会被执行
注意:需要监听的这个变量需要在data里面声明,如果不声明就会报错。

引用了:www.jianshu.com/p/8314ccd03…

data和computed的区别:
  1. data中的属性并不会随赋值变量的改动而改动
  2. 当需要这种随赋值变量的改动而改动的时候,还是用计算属性computed合适
    引用了:blog.csdn.net/weixin_3440…
watch和computed的区别:

computed是用于定义基于数据之上的数据
watch是在某个数据变化时做一些操作,如果做的事情是更新其它数据,那其实和把这个要更新的数据项定义成computed是一样的,这个时候用computed更有可读性,虽然技术上讲watch也可以实现。
你也可以被watch的数据变化时做其它事情,比如调用一个方法,这个是computed做不到也不应该做的。
总结:

  1. 如果一个数据依赖于其它数据,那么把这个数据设计为computed
  2. computed的值有缓存,只有它依赖的属性值发生变化,computed的值才会重新计算
  3. 如果你需要在某个数据变化时做一些事情,使用watch来观察这个数据变化
  4. computed能实现的功能,watch都能实现;但是watch能实现的功能,computed不能实现,比如watch可以进行异步操作

引用了:segmentfault.com/q/101000000…

beforeCreate created [可以获取数据及方法]
beforeMount mounted [可以获取到真实的DOM]
beforeUpdate updated [数据更新执行]
beforeDestroy destroyed [销毁vue实例,不再具有双向数据绑定的特点]

VUE什么情况下触发destroy

我们从destroy的字面意思可知,中文意为是“销毁”的意思,,我们常用来销毁一些监听事件及定时函数。
一般2种情况下触发destroy来销毁组件:

  1. 没有使用keep-alive时的路由切换
  2. 将该组件的v-if置为false