如何聲明 vue.js mounted 中的方法?作為對象屬性,通過 this 上下文訪問組件實例;作為方法選項,包含在 methods 對象中,同樣通過 this 訪問組件實例。
如何在 Vue.js 的 mounted 中聲明方法
在 Vue.js 生命周期鉤子函數(shù) mounted 中聲明方法是一種在組件掛載后執(zhí)行代碼的常見方法。下面介紹兩種聲明方法的方式:
1. 作為對象屬性
export default {
mounted() {
this.myMethod()
},
methods: {
myMethod() {
// 方法實現(xiàn)
}
}
}
登錄后復制
2. 作為方法選項
export default {
mounted() {
this.myMethod()
},
methods: {
myMethod() {
// 方法實現(xiàn)
}
}
}
登錄后復制
無論使用哪種方法,聲明的方法都可以通過 this 上下文訪問組件實例。
示例
export default {
mounted() {
this.logComponentMounted()
},
methods: {
logComponentMounted() {
console.log('組件已掛載')
}
}
}
登錄后復制
在上面的示例中,logComponentMounted 方法在組件掛載后調(diào)用,并輸出一條日志消息到控制臺。






