自学内容网 自学内容网

vue 组件数据加载解析顺序

组件数据加载解析顺序

实例初始化完成、props 解析 -> beforeCreate -> 响应式数据、计算属性、方法和侦听器设置完成 -> created -> 判断是否有渲染模版 -> beforeMount -> 组件挂载 -> mounted

  • created之前,响应式数据、计算属性、方法和侦听器设置完成,但是方法、计算属性并不会执行,没有immediate: true的侦听器也不会执行;
  • 只有用到计算属性时,才会去执行计算属性的方法
  • 组件内外部使用push,$set,不修改原数组对象,会使得watch中的newValue等于oldValue,JSON.stringify(newValue) === JSON.stringify(oldValue)
  • watch加了immediate: true,先执行响应式数据初始化,立即触发watch后,走到created生命周期。
  • 侦听器依次设置时,immediate: true的立即执行,执行后再继续设置其他的侦听器,也就是说,当immediate立即执行的监听,当某些数据变更后,如果侦听器还没有设置,就不会执行
  • 没有immediate: true,的watch,触发时机是晚于created、mounted的,当数据再次发生变化后,beforeUpdate之前执行;
  • watch加了immediate: true,可以监听到响应式数据初始化后的变化。
  • 不要在选项 property 或回调上使用箭头函数,比如 created: () => console.log(this.a) 或 vm.$watch(‘a’, newValue => this.myMethod())。因为箭头函数并没有 this,this 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致 Uncaught TypeError: Cannot read property of undefined 或 Uncaught TypeError: this.myMethod is not a function 之类的错误。
import Vue from "vue";

new Vue({
  el: "#app",
  template: `<div>
    <div>{{computedCount}}</div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  watch: {
    count: {
      handler() {
        console.log('watch');
      },
      immediate: true,
    }
  },
  computed: {
    computedCount() {
      console.log('computed');
      return this.count + 1;
    }
  },
  created() {
    console.log('created');
  },
  mounted() {
    console.log('mounted');
  },
});


watch -> created -> computed -> mounted


new Vue({
  el: "#app",
  template: `<div>
    <div></div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  watch: {
    count: {
      handler() {
        console.log('watch');
      },
      immediate: true,
    }
  },
  computed: {
    computedCount() {
      console.log('computed');
      return this.count + 1;
    }
  },
  created() {
    console.log('created');
  },
  mounted() {
    console.log('mounted');
  },
});

watch -> created -> mounted


new Vue({
  el: "#app",
  template: `<div>
    <div></div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  watch: {
    count: {
      handler() {
        console.log('watch');
      },
      immediate: true,
    }
  },
  computed: {
    computedCount() {
      console.log('computed');
      return this.count + 1;
    }
  },
  created() {
    console.log('created');
  },
  mounted() {
    console.log('mounted');
    this.computedCount
  },
});

watch -> created -> mounted -> computed


原文地址:https://blog.csdn.net/weixin_45549481/article/details/136371918

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!