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 指令