vue 初始化方法 create,beforeMount,mount,computed,watch 方法执行顺序及使用场景

前言:vue 存在一些基本属性和相关对象如果合理使用,可以避免代码混乱

VUE初始化属性和方法

执行顺序

create
beforeMount
computed
mounted
watch

方法说明

created执行时挂载阶段还没有开始,模版还没有渲染成html,所以无法获取元素。created钩子函数主要用来初始化数据。
beforeMount 这一步的时候,模版已经在内存中编译好了,但是尚未挂载到页面中去。
computed是在DOM执行完成后立马执行(如:赋值)
mounted钩子函数一般用来向后端发起请求,拿到数据后做一些业务处理。该函数在模版渲染完成后才被调用。DOM操作一般是在mounted钩子函数中进行。
watch用于检测vue实例上数据的变动
默认加载的时候先computed再watch,不执行methods;等触发某一事件后,则是:先methods再watch。
methods方法有一定的触发条件,如click等。
所有方法都应该在methods里定义,在mounted或created里面使用this调用,用这种方法实现初始化。

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

代码实例:

<template>
  <div>

    <!-- 监听对象变化 -->

    输入名称:<input type="text" v-model="name"></input>
    监听数据变化赋值:{{ name1 }}

    <!-- 监听对象变化  用函数处理 -->

    输入名称:<input type="text" v-model="inputValue"></input>
    监听数据变化赋值:{{ watchInputValue }}


    <div id="aaa">{{ aaa }}</div>


  </div>
</template>
<script>
export default {
  name: "test",
  data() {
    return {
      name: "",
      name1: "",
      aaa: "1111",
      inputValue: "",
      watchInputValue: "",
      user: "11111",
      show1: false,
      sites: [
        {name: 'Runoob'},
        {name: 'Google'},
        {name: 'Taobao'}
      ]
    }
  },
  methods: {
    test() {
      console.log("test 执行了")
    },
    watchInputNameFunc(newName, oldName) {
      console.log(newName) // this.inputValue的值
      this.watchInputValue = this.inputValue // 也可以写成:this.watchInputValue = newName
      //alert(newName);
    }
  },
  created() {
    this.test();
    console.log("dom节点中的值", document.getElementById("aaa"));
  },
  watch: {
    inputValue: 'watchInputNameFunc',// 也可以写成:  'inputValue': 'watchInputNameFunc'
    name: {
      handler(newName, oldName) {
        console.log("name 执行了");
        this.name1 = newName
      }
    }
  },
  computed() {
    console.log("computed 执行了")
  },
  beforeMount() {
    console.log("beforeMount 执行了")
  },
  mounted() {
    console.log("mounted 执行了");
    console.log("dom节点中的值", document.getElementById("aaa"));
  }
}
</script>

<style scoped>

</style>

备注说明

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

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

computed:(watch监听的)
watch:immediate
create
beforeMount
computed
mounted
watch

参考:https://blog.csdn.net/m0_49016709/article/details/122066570

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值