watch、computed、created、beforeMount、mounted的执行顺序

1,749 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第 4 天,点击查看活动详情

在上一篇文章中介绍了 Vue 生命周期钩子函数的执行顺序 juejin.cn/post/710930…
这里再继续对 watch、computed、和created 钩子函数的执行顺序进行补充介绍

正常的执行顺序 created -> beforeMount -> computed -> mounted -> watch

<template>
  <div class="hello">
   <h1>{{ msg }}</h1>
   <div>
     {{arrSum}}
   </div>
  </div>
</template>

<script>
export default {
  name: 'Test',
  data() {
    return {
      msg: '前端代码仔',
      arr: [1,2,3,4,5,6,7,8,9]
    }
  },
  watch: {
      msg: {
          handler(val) {
          console.log('watch:msg');
        },
      },
  },
  created() {
    console.log('created')
    this.msg = '111'
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted() {
    console.log('mounted')
  },
  computed: {
      arrSum() {
        console.log('computed');
        return this.arr.reduce((total,item)=>(total+=item,total),0)
      },
  },
}
</script>

image.png created: 执行时挂载阶段还没有开始,模版还没有渲染成html,所以无法获取元素。created钩子函数主要用来初始化数据。
beforeMount: 模版已经在内存中编译好了,但是尚未挂载到页面中去。
computed: 是在DOM执行完成后立马执行(如:赋值)
mounted: 模版渲染完成后才被调用。DOM操作一般是在mounted钩子函数中进行。
watch用于检测vue实例上数据的变动
默认加载的时候先computed再watch,不执行methods;等触发某一事件后,则是:先methods再watch。

设置了watch immediate:true 他的优先级会提到最前面

<template>
  <div class="hello">
   <h1>{{ msg }}</h1>
   <div>
     {{arrSum}}
   </div>
  </div>
</template>

<script>
export default {
  name: 'Test',
  data() {
    return {
      msg: '前端代码仔',
      arr: [1,2,3,4,5,6,7,8,9]
    }
  },
  watch: {
      msg: {
          handler(val) {
          console.log('watch:msg');
        },
          immediate: true,
      },
      arrSum: {
        handler(val) {
          console.log('watch:computed-arrSum');
        },
      }
  },
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted() {
    console.log('mounted')
  },
  computed: {
      arrSum() {
        console.log('computed');
        return this.arr.reduce((total,item)=>(total+=item,total),0)
      },
  },
}
</script>

image.png

设置了watch immediate:true,监听的是计算属性的值 他的优先级应该会提到最前面,但是vue默认先computed 再执行watch

<template>
  <div class="hello">
   <h1>{{ msg }}</h1>
   <div>
     {{arrSum}}
   </div>
  </div>
</template>

<script>
export default {
  name: 'Test',
  data() {
    return {
      msg: '前端代码仔',
      arr: [1,2,3,4,5,6,7,8,9]
    }
  },
  watch: {
      msg: {
          handler(val) {
          console.log('watch:msg');
        },
      },
      arrSum: {
        handler(val) {
          console.log('watch:computed');
        },
        immediate: true,
      }
  },
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted() {
    console.log('mounted')
  },
  computed: {
      arrSum() {
        console.log('computed');
        return this.arr.reduce((total,item)=>(total+=item,total),0)
      },
  },
}
</script>

image.png