Vue.js中方法和计算值的主要区别是什么?

在我看来,它们是一样的,是可以互换的。


当前回答

以下是ve3文档所说的-查看一个例子:

对于最终结果,这两种方法确实完全相同。然而,不同之处在于计算属性是基于它们的响应性依赖项进行缓存的。计算属性只有在其响应性依赖项发生更改时才会重新计算。[…相比之下,方法调用将始终在重新呈现发生时运行该函数。

额外的链接

方法 计算属性

其他回答

computed和methods之间的区别在于,当你在computed中定义一个函数时,它只在答案改变时才从头执行该函数,而methods在每次调用时都从头执行该函数。

根据vueJs文档,一个简单的方法是:

相比之下,每当重新呈现发生时,方法调用将始终运行该函数。

而计算属性只有在其响应性依赖项发生更改时才会重新计算

在vue 3附带的vue组合API中,可以作为vue 2的插件使用,方法和计算属性是不同的语法:

例子:

计算:

它是一个默认接受getter回调作为参数的函数,并根据其他属性(如ref, reactive或store state)返回一个不可变的ref。

import {computed,ref} from 'vue'

export default{

setup(){
  const count=ref(0);
  
  const doubleCount=computed(()=>count.value*2) 

 return {count,doubleCount} //expose the properties to the template 
 }
}

方法

它们是纯javascript函数,在Vue和vanilla js中以相同的方式表现,它们暴露在模板中并用作事件处理程序,它们不应该用于渲染目的,这可能会导致一些问题,如无限渲染。

import {computed,ref} from 'vue'

export default{

setup(){
  const count=ref(0);
  
  const doubleCount=computed(()=>count.value*2) 
 
  function increment(){
   ref.value++
 }

 return {count,doubleCount,increment} //expose the properties/functions to the template 
 }
}

区别在于:

计算:

它被计算为不可变属性,而不是函数 它观察另一个属性并基于该属性返回一个属性。 它不能带参数。 可以使用watch属性观看它

方法:

用于重构computed/watcher属性或其他函数中的代码 用作事件处理程序 为了避免呈现问题,不应该在模板中调用它。

以下是ve3文档所说的-查看一个例子:

对于最终结果,这两种方法确实完全相同。然而,不同之处在于计算属性是基于它们的响应性依赖项进行缓存的。计算属性只有在其响应性依赖项发生更改时才会重新计算。[…相比之下,方法调用将始终在重新呈现发生时运行该函数。

额外的链接

方法 计算属性

@gleenk需要一个实际的例子来说明方法和计算属性之间的缓存和依赖关系的差异,我将展示一个简单的场景:

app.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 & addToBmethod and the computed properties addToAcomputed & addToBcomputed all add +20 (i.e. the age value) to either a or b. Regarding the methods, they are both called every time an action has been performed on any of 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 addToAcomputed or addToBcomputed, respectively.

方法和计算描述看起来非常相似,但正如@Abdullah Khan已经指定的那样,它们不是一回事!现在让我们尝试添加一些html来一起执行所有内容,看看有什么不同。

方法案例演示

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>

解释结果

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 practice because 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.

Computed属性案例演示

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>

解释结果

When I click on the button "Add to A", only the computed property addToAcomputed is 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.