vue.mouted的两种写法

在Vue中,mounted生命周期钩子可以有两种写法:

  1. 方法写法:
    1
    2
    3
    4
    js
    mounted() {
    // ...
    }
  2. 对象写法:
    1
    2
    3
    4
    js
    mounted: function() {
    // ...
    }
    这两种写法的区别是:
    方法写法:
  • 简洁
  • 适合较简单的逻辑
  • this指向当前Vue实例

对象写法:

  • 可以访问arguments
  • 可以命名(比如mounted: doSomething)
  • 可读性稍差
  • 需要手动绑定this(使用.bind(this)或箭头函数)

除非需要访问arguments或做更复杂的逻辑,方法写法是更优雅的选择。
举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// 方法写法
mounted() {
console.log(this.$el) // Vue实例
}

// 对象写法
mounted: function() {
console.log(this.$el) // undefined, 需要绑定this
console.log(arguments)
}.bind(this)

// 或使用箭头函数
mounted: () => {
console.log(this.$el) // Vue实例
}

vue.mouted的两种写法
http://oowatermelon.github.io/OoWaterMelonS/2023/04/18/vue-mouted的两种写法/
作者
OoWaterMelonS Shao
发布于
2023年4月18日
许可协议