Vue 'methods' 選項
示例
使用 methods
選項中的方法來切換訊息。
export default {
data() {
return {
msg: 'Hello World!',
showMsg: false
};
},
methods: {
toggleMsg() {
this.showMsg = !this.showMsg;
}
}
};
執行示例 »
定義和用法
methods
選項是一個物件,其中包含在 Vue 例項上宣告的所有方法。
方法可以直接(無需 this
關鍵字)在 Vue 應用程式的 <template>
中呼叫,例如,當方法設定為在事件發生時執行時,使用 v-on
指令。
必須使用 this
關鍵字才能在 Vue 例項內部呼叫方法,例如,當一個方法被另一個方法呼叫時。
注意: 宣告方法時應避免使用箭頭函式,因為透過 this
關鍵字無法從該函式內部訪問 Vue 例項。
相關頁面
Vue 教程: Vue 方法
Vue 教程: Vue v-on 指令