首页 文章

方法vs在Vue中计算

提问于
浏览
76

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

它们看起来一样,可以互换 .

4 回答

  • 27

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

    Computed Property

    计算值的更合适的名称是computed property . 实际上,当Vue被实例化时,计算属性将被转换为具有getter且有时是setter的Vue的属性 . 基本上,您可以将计算值视为派生值,只要更新用于计算它的其中一个基础值,它就会自动更新 . 你没有调用计算机,它不是documentation的经典例子:

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

    哪个在DOM中引用如下:

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

    计算值对于操纵Vue上存在的数据非常有 Value . 无论何时您想要过滤或转换数据,通常都会为此目的使用计算值 .

    data:{
        names: ["Bob", "Billy", "Mary", "Jane"]
    },
    computed:{
        startsWithB(){
            return this.names.filter(n => n.startsWith("B"))
        }
    }
    
    <p v-for="name in startsWithB">{{name}}</p>
    

    计算值也会被缓存,以避免重复计算在未更改时不需要重新计算的值(例如,它可能不在循环中) .

    Method

    方法只是绑定到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的documentation真的很好,很容易访问 . 我推荐它 .

  • 8

    由于@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;
            }
        }
    });
    

    这里我们有2个方法和2个计算属性执行相同的任务 . 方法 addToAmethodaddToBmethod 和计算属性 addToAcomputedaddToBcomputed 都将20(即 age 值)添加到 ab . 关于这些方法,每次对任何列出的属性执行操作时都会调用它们,即使某个特定方法的依赖关系没有更改也是如此 . 对于计算属性,仅在依赖关系发生变化时才执行代码;例如,引用A或B的特定属性值之一将分别触发 addToAcomputedaddToBcomputed .

    方法和计算的描述看起来非常相似,但是@Abdullah Khan已经specified了, they are not the same thing !现在让我们尝试添加一些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>
    

    解释结果

    当我点击按钮 "Add to A" 时,调用所有方法(参见上面的控制台日志屏幕结果), addToBmethod() 也被执行但我没有按 "Add to B" 按钮;引用B的属性值没有改变 . 如果我们决定单击按钮 "Add to B" ,则会出现相同的行为,因为将再次调用这两个方法而不依赖于依赖项更改 . 根据这种情况,这是 bad practice 因为我们每次都在执行方法,即使依赖关系没有改变 . 这实际上是资源消耗,因为没有用于未更改的属性值的缓存 .

    method

    button method

    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>
    

    解释结果

    当我单击按钮 "Add to A" 时,只调用计算属性 addToAcomputed ,因为正如我们已经说过的那样,只有当依赖项发生了变化时才会执行计算属性 . 由于我没有按下按钮 "Add to B" 并且B的age属性值没有改变,因此没有理由调用并执行计算属性 addToBcomputed . 因此,在某种意义上,计算属性维护B属性的"same unchanged"值,就像一种缓存一样 . 在这种情况下,这是考虑 good practice .

    computed

    button computed

  • 109

    来自docs

    ..computed属性根据其依赖项进行缓存 . 计算属性仅在其某些依赖项发生更改时才会重新计算 .

    如果您希望缓存数据,另一方面如果您不希望缓存数据,请使用简单的Method属性 .

  • 1

    Computed Properties

    计算属性也称为计算值 . 这意味着,他们可以随时更新并进行更改 . 此外,它还会缓存数据,直到更改为止 . 实例化Vue时,计算属性将转换为属性 .

    还有一件事我想分享,你不能在计算属性中传递任何参数,这就是为什么在调用任何计算机属性时不需要括号 .

    Methods

    方法与功能相同,工作方式相同 . 此外,除非您调用它,否则方法无效 . 此外,与所有javascript函数一样,它接受参数,并在每次调用时重新进行评估 . 在那之后,他们无法缓存值

    在方法中,调用括号就在那里,您可以在其中发送一个或多个参数 .

相关问题