我想知道在数据中声明的方法与在方法中声明的方法有什么区别?
var app = new Vue({
el: "#vue-app",
data: {
name: function() {
console.log("Alex");
}
},
methods: {
name: function() {
console.log("Alex");
}
}
});
最佳答案
tl;dr 如果您的内部只有一个 console.log("Alex")
,它们的工作原理是一样的。但是如果你在它们里面有一个this
,它们就会有很大的不同。
首先,Vue data
对象应该是没有方法的纯 JavaScript 对象。来自 the API docs :
The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it “reactive”. The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.
因此,即使它有效,我也会在 methods
中声明它们以遵循 POLA .
一个关键的区别:
但是,更重要的是,有一个关键因素:方法绑定(bind)到 Vue 实例。这意味着 this
内部方法 总是指向当前的 Vue 实例。
new Vue({
el: '#app',
data: {
nameData: function() {
console.log("nameData", this.otherMethod()) // doesn't work
},
},
methods: {
nameMethod: function() {
console.log("nameMethod", this.otherMethod()); // works
},
otherMethod() {
return "I am other method";
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button @click="nameData">invoke nameData</button><br>
<button @click="nameMethod">invoke nameMethod</button>
</div>
又一个例子:
new Vue({
el: '#app',
data: {
id: 3,
ids: [1,2,3,4],
equalsIdData: function(i) {
return this.id === i;
},
},
methods: {
equalsIdMethod: function(i) {
return this.id === i;
},
yetAnotherMethod: function() {
console.log('equalsIdMethod:', this.ids.filter(this.equalsIdMethod)); // filters correctly
console.log('equalsIdData:', this.ids.filter(this.equalsIdData)); // filters incorrectly
},
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button @click="yetAnotherMethod">invoke yetAnotherMethod</button>
</div>
关于javascript - vue.js 数据中的方法和方法中的方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804235/