Vue中如何定义JavaScript函数?

发表时间: 2023-09-19 14:39

在 methods 中定义方法

我们可以使用 methods 属性给 Vue 定义方法,methods 的基本语法:

var vm = new Vue({

methods:{

// 在此时定义方法,方法之间使用逗号分隔

方法名:function(){}

});

示例:

例如在 methods 中定义一个名为 show 的方法:

methods:{

show: function(){

console.log("显示内容")

}

}

在方法中访问属性

methods 方法中访问 data 的数据,可以直接通过 this.属性名 的形式来访问。

示例:

例如我们在 show 方法中,访问 number 属性,可以直接通过 this.number 形式访问,其中 this 表示的就是Vue 实例对象:

<script>

new Vue({

el: '#app',

data(){

return{

number: 100

}

},

methods:{

show: function(){

console.log(this.number);

}

}

});

</script>