方法vs在Vue中计算 [英] Method vs Computed in Vue

查看:166
本文介绍了方法vs在Vue中计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the main difference between a method and a computed value in Vue.js?

它们看起来相同且可以互换。

They look the same and interchangeable.

推荐答案

计算值和方法在Vue中非常不同,在大多数情况下绝对不可互换。

Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.

计算属性

计算值的更合适的名称是计算属性。事实上,当Vue被实例化时,计算属性将被转换为具有getter的Vue属性,有时也会被设置为setter。基本上,您可以将计算值视为派生值,只要更新用于计算它的其中一个基础值,它就会自动更新。你不调用一个计算机,它不接受任何参数。您可以像引用数据属性一样引用计算属性。以下是文档中的经典示例:

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 call a 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:

computed: {
  // a computed getter
  reversedMessage: function () {
    // `this` points to the vm instance
    return this.message.split('').reverse().join('')
  }
}

在DOM中引用的是这样的:

Which is referenced in the DOM like this:

<p>Computed reversed message: "{{ reversedMessage }}"</p>

计算值对于操纵Vue上存在的数据非常有价值。每当您想要过滤或转换数据时,通常会为此目的使用计算值。

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.

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).

方法

方法只是绑定到Vue实例的函数。它只会在您明确调用它时进行评估。像所有javascript函数一样,它接受参数,并在每次调用时重新进行评估。在任何函数都有用的相同情况下,方法很有用。

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.

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的文档非常好且易于访问。我推荐它。

Vue's documentation is really good and easily accessible. I recommend it.

这篇关于方法vs在Vue中计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆