Javascript Vue 中的方法与计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44350862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method vs Computed in Vue
提问by Bootstrap4
What is the main difference between a method and a computed value in Vue.js?
Vue.js 中方法和计算值之间的主要区别是什么?
They look the same and interchangeable.
它们看起来相同并且可以互换。
回答by Bert
Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.
Vue 中的计算值和方法非常不同,并且在大多数情况下绝对不能互换。
Computed Property
计算属性
A more appropriate name for a computed value is a computed property. In fact, when the Vue is instantiated, computed properties are converted into a property of the Vue with a getter and sometimes a setter. Basically you can think of a computed value as a derived value that will be automatically updated whenever one of the underlying values used to calculate it is updated. You don't calla computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Here's the classic example from the documentation:
计算值更合适的名称是计算属性。事实上,当 Vue 被实例化时,计算属性被转换成 Vue 的属性,带有一个 getter,有时还有一个 setter。基本上,您可以将计算值视为派生值,只要用于计算它的基础值之一更新,该值就会自动更新。你不调用一个计算,它不接受任何参数。您可以像引用数据属性一样引用计算属性。这是文档中的经典示例:
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
Which is referenced in the DOM like this:
在 DOM 中是这样引用的:
<p>Computed reversed message: "{{ reversedMessage }}"</p>
Computed values are very valuable for manipulating data that exists on your Vue. Whenever you want to filter or transform your data, typically you will use a computed value for that purpose.
计算值对于操作 Vue 上存在的数据非常有价值。每当您想要过滤或转换数据时,通常都会为此目的使用计算值。
data:{
names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
startsWithB(){
return this.names.filter(n => n.startsWith("B"))
}
}
<p v-for="name in startsWithB">{{name}}</p>
Computed values are also cached to avoid repetitively calculating a value that doesn't need to be re-calculated when it hasn't changed (as it might not be in a loop for example).
计算值也被缓存以避免重复计算一个值,当它没有改变时不需要重新计算(例如它可能不在循环中)。
Method
方法
A method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. Like all javascript functions it accepts parameters and will be re-evaluated every time it's called. Methods are useful in the same situations any function is useful.
方法只是绑定到 Vue 实例的函数。只有在您明确调用它时才会对其进行评估。像所有 javascript 函数一样,它接受参数并且每次调用时都会重新评估。方法在相同情况下很有用,任何函数都有用。
data:{
names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
startsWithB(){
return this.startsWithChar("B")
},
startsWithM(){
return this.startsWithChar("M")
}
},
methods:{
startsWithChar(whichChar){
return this.names.filter(n => n.startsWith(whichCharacter))
}
}
Vue's documentationis really good and easily accessible. I recommend it.
Vue 的文档非常好且易于访问。我推荐它。
回答by Giulio Bambini
As @gleenk asked for a practical example to make evident the cache and dependency differences between methods and computed properties, I'll show a simple scenario:
由于@gleenk 要求提供一个实际示例来明确方法和计算属性之间的缓存和依赖项差异,因此我将展示一个简单的场景:
app.js
应用程序.js
new Vue({
el: '#vue-app',
data: {
a: 0,
b: 0,
age: 20
},
methods: {
addToAmethod: function(){
console.log('addToAmethod');
return this.a + this.age;
},
addToBmethod: function(){
console.log('addToBmethod');
return this.b + this.age;
}
},
computed: {
addToAcomputed: function(){
console.log('addToAcomputed');
return this.a + this.age;
},
addToBcomputed: function(){
console.log('addToBcomputed');
return this.b + this.age;
}
}
});
Here we have 2 methods and 2 computed properties that perform the same task. The methods addToAmethod& addToBmethodand the computed properties addToAcomputed& addToBcomputedall add +20 (i.e. the agevalue) to either aor b. Regarding the methods, they are bothcalled everytime an action has been performed on anyof the listed properties, even if the dependencies for one specific method have not changed. For the computed properties, the code is executed only when a dependency has changed; for example, one of the specific property values that refers to A or B will trigger addToAcomputedor addToBcomputed, respectively.
这里我们有 2 个方法和 2 个计算属性来执行相同的任务。方法addToAmethod&addToBmethod和计算属性addToAcomputed&addToBcomputed都将 +20(即age值)添加到a或b。关于方法,每次对任何列出的属性执行操作时都会调用它们,即使某个特定方法的依赖项没有改变。对于计算属性,只有在依赖项发生变化时才会执行代码;例如,引用 A 或 B 的特定属性值之一将分别触发或。addToAcomputedaddToBcomputed
The method and computed descriptions seem pretty similar, but as @Abdullah Khan has already specifiedit, they are not the same thing! Now let's try to add some html to execute everything together and see where the difference is.
方法和计算描述看起来非常相似,但正如@Abdullah Khan 已经指定的那样,它们不是一回事!现在让我们尝试添加一些 html 来一起执行所有内容,看看有什么不同。
The Method case demo
方法案例演示
new Vue({
el: '#vue-app',
data: {
a: 0,
b: 0,
age: 20
},
methods: {
addToAmethod: function(){
console.log('addToAmethod');
return this.a + this.age;
},
addToBmethod: function(){
console.log('addToBmethod');
return this.b + this.age;
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>VueJS Methods - stackoverflow</title>
<link href="style.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>
</head>
<body>
<div id="vue-app">
<h1>Methods</h1>
<button v-on:click="a++">Add to A</button>
<button v-on:click="b++">Add to B</button>
<p>Age + A = {{ addToAmethod() }}</p>
<p>Age + B = {{ addToBmethod() }}</p>
</div>
</body>
<script src="app.js"></script>
</html>
The explained result
解释的结果
When I click on the button "Add to A", all the methods are called (see the console log screen result above), the addToBmethod()is also executed but I didn't press the "Add to B"button; the property value that refers to B has not changed. The same behaviour comes if we decide to click the button "Add to B", because again both the methods will be called independently of dependency changes. According to this scenario this is bad practicebecause we are executing the methods every time, even when dependencies have not changed. This is really resource consuming because there is not a cache for property values that have not changed.
当我单击“添加到 A”按钮时,所有方法都被调用(参见上面的控制台日志屏幕结果),addToBmethod()也会执行,但我没有按下“添加到 B”按钮;引用 B 的属性值没有改变。如果我们决定单击按钮“添加到 B”,则会出现相同的行为,因为这两个方法将再次独立于依赖项更改而被调用。根据这种情况,这是不好的做法,因为我们每次都在执行这些方法,即使依赖项没有改变。这确实很消耗资源,因为没有对未更改的属性值进行缓存。




The Computed property case demo
计算属性案例演示
new Vue({
el: '#vue-app',
data: {
a: 0,
b: 0,
age: 20
},
computed: {
addToAcomputed: function(){
console.log('addToAcomputed');
return this.a + this.age;
},
addToBcomputed: function(){
console.log('addToBcomputed');
return this.b + this.age;
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>VueJS Computed properties - stackoverflow</title>
<link href="style.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>
</head>
<body>
<div id="vue-app">
<h1>Computed Properties</h1>
<button v-on:click="a++">Add to A</button>
<button v-on:click="b++">Add to B</button>
<p>Age + A = {{ addToAcomputed }}</p>
<p>Age + B = {{ addToBcomputed }}</p>
</div>
</body>
<script src="app.js"></script>
</html>
The explained result
解释的结果
When I click on the button "Add to A", only the computed property addToAcomputedis called because, as we already said, the computed properties are executed only when a dependency has changed. And since I didn't press the button "Add to B"and the age property value for B has not changed, there is no reason to call and execute the computed property addToBcomputed. So, in a certain sense, the computed property is maintaining the "same unchanged" value for the B property like a kind of cache. And in this circumstance this is consider good practice.
当我单击“添加到 A”按钮时,只addToAcomputed调用计算属性,因为正如我们已经说过的,计算属性仅在依赖项发生更改时执行。而且由于我没有按下“添加到 B”按钮并且B的 age 属性值没有改变,所以没有理由调用和执行计算属性addToBcomputed。因此,从某种意义上说,计算属性就像一种缓存一样为 B 属性维护“相同的不变”值。在这种情况下,这是一种很好的做法。




回答by Abdullah Khan
From the docs
来自 docs
..computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.
..计算属性根据它们的依赖关系进行缓存。计算属性只会在其某些依赖项发生更改时重新评估。
If you want data to be cached use Computed properties on the other hand if you don't want data to be cached use simple Method properties.
如果您希望缓存数据,请使用 Computed 属性,另一方面,如果您不想缓存数据,请使用简单的 Method 属性。
回答by PALLAMOLLA SAI
One of difference between computed and method. Suppose we have a function which will return counter value.(counter is just variable). Let's look how function behaves in both computedand method
计算和方法之间的区别之一。假设我们有一个函数将返回计数器值。(计数器只是变量)。让我们看看函数在计算和方法中的行为
Computed
计算
At first time of execution the code inside the function will be executed and vuejs will store the counter value in cache(for accessing faster). But when we are again calling the function vuejs will not again execute the code written inside of that function. It first checks any changes made to the counter or not. If any changes made then only it will re-execute the code which is inside that function. If there are no changes made to the counter vuejs will not again execute the function. It will simply return the previous result from the cache.
在第一次执行时,函数内的代码将被执行,vuejs 会将计数器值存储在缓存中(以便更快地访问)。但是当我们再次调用该函数时,vuejs 将不会再次执行该函数内部编写的代码。它首先检查对计数器所做的任何更改。如果进行了任何更改,那么它只会重新执行该函数内的代码。如果没有对计数器进行任何更改,vuejs 将不会再次执行该函数。它将简单地从缓存中返回先前的结果。
Method
方法
This is just like a normal method in the javascript. Whenever we call the method it will always execute the code inside the function irrespective of changes made to the counter.
这就像javascript中的普通方法一样。每当我们调用该方法时,它总是会执行函数内部的代码,而不管对计数器所做的更改。
Method will always reexecutes the code irrespective of changes in the code. where as computed will reexecute the code then only if one of it's dependency's values changed. Otherwise it will give us the previous result from the cache without reexecuting
无论代码如何更改,方法都会始终重新执行代码。只有当它的依赖值之一发生变化时,计算才会重新执行代码。否则它会从缓存中给我们以前的结果,而无需重新执行
回答by Diego Pereira
Here's a breakdown of this question.
这是这个问题的细分。
When to use methods
何时使用方法
- To react to some event happening in the DOM
- To call a function when something happens in your component.
- You can call a method from computed properties or watchers.
- 对 DOM 中发生的某些事件做出反应
- 在组件中发生某些事情时调用函数。
- 您可以从计算属性或观察者调用方法。
When to use computed properties
何时使用计算属性
- You need to compose new data from existing data sources
- You have a variable you use in your template that's built from one or more data properties
- You want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes)
- You need to reference a value from the template. In this case, creating a computed property is the best thing, because it's cached.
- You need to listen to changes of more than one data property
- 您需要从现有数据源组合新数据
- 您在模板中使用了一个由一个或多个数据属性构建的变量
- 您希望将复杂的嵌套属性名称简化为更易读且易于使用的名称(但在原始属性更改时更新它)
- 您需要从模板中引用一个值。在这种情况下,创建计算属性是最好的选择,因为它是缓存的。
- 您需要监听多个数据属性的变化
回答by Rajat
Computed Properties
计算属性
Computed properties are called computed value as well. It means, they update and can be changed anytime. Also, it caches the data until it changes. When the Vue is instantiated, computed properties are converted into a property.
计算属性也称为计算值。这意味着,它们会更新并且可以随时更改。此外,它会缓存数据,直到数据发生变化。当 Vue 被实例化时,计算属性被转换为属性。
One more thing I want to share, You cannot pass any parameter in the computed properties that's why while calling any computer property no parenthesis required.
我想分享的另一件事是,您不能在计算属性中传递任何参数,这就是调用任何计算机属性时不需要括号的原因。
Methods
方法
Methods are the same as function and work the same way. Besides, a method does nothing unless you call it. Also, like all javascript functions, it accepts parameters and will be re-evaluated every time it's called. After that, they can't cache values
方法与功能相同,工作方式相同。此外,除非你调用一个方法,否则它什么都不做。此外,与所有 javascript 函数一样,它接受参数,并且每次调用时都会重新评估。之后,他们无法缓存值
In the method calling parenthesis is there and you can send one or more parameter in that.
在调用括号的方法中,您可以在其中发送一个或多个参数。
回答by DarkLite1
Stumbled upon the same question. To me it's more clear like this:
偶然发现了同样的问题。对我来说,这样更清楚:
- When Vue.js sees the
v-on directivefollowed by a method, it knows exactly which methodto call and whento call it.
- 当 Vue.js 看到
v-on directive后面跟着一个方法时,它确切地知道要调用哪个方法以及何时调用它。
<button v-on:click="clearMessage">Clear message</button> // @click
// method clearMessage is only called on a click on this button
<input v-model="message" @keyup.esc="clearMessage" @keyup.enter="alertMessage" />
/* The method clearMessage is only called on pressing the escape key
and the alertMessage method on pressing the enter key */
- When a method is called without the
v-on directiveit will be called every time an event is triggeredon the page that updates the DOM (or simply needs to re-render a part of the page). Even when that method has nothing to do with the event being triggered.
- 当一个方法在没有
v-on directiveDOM 的情况下被调用时,每次在更新 DOM 的页面上触发事件时都会调用它(或者只是需要重新渲染页面的一部分)。即使该方法与触发的事件无关。
<p>Uppercase message: {{ messageUppercase() }}</p>
methods: {
messageUppercase() {
console.log("messageUpercase");
return this.message.toUpperCase();
}
}
/* The method `messageUppercase()` is called on every button click, mouse hover
or other event that is defined on the page with the `v-on directive`. So every
time the page re-renders.*/
- A Computed property is only calledwhen a property value is changed that is being referenced by the
thiswordin its function definition.
- 计算属性仅在其函数定义中的
this单词所引用的属性值发生更改时才被调用。
<p>Uppercase message: {{ messageUppercase }}</p>
data() {
return {
message: "I love Vue.js"
}
},
computed: {
messageUppercase() {
console.log("messageUpercase");
return this.message.toUpperCase();
}
}
/* The computed property messageUppercase is only called when the propery message is
changed. Not on other events (clicks, mouse hovers,..) unless of course a specific
event changes the value of message. */
The take away here is that it's best practice to use the computedproperties in case a method is not being called with the v-on directive.
这里的要点是,如果computed没有使用v-on directive.

