The difference between computed and methods in Vue

Vue in computed It can be used for simple splicing of data to be displayed


computed and methods

The task of splicing and displaying data can also be completed with methods, but when the data of the page changes, the methods in methods will be called again (causing unnecessary performance consumption), while the methods in methods will only be called when the data related to itself changes

A simple example

computed is only called during initialization
  • computed is only called during initialization
  • methods will be called when the data changes, even if the changed data has nothing to do with itself

Test source

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>computed Use</title>
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
    <div id="root">
    </div>
    <script>

        var vm = new Vue({
            el: "#root",
            data: {
                name: "zhaozhao",
                age: 13,
                hobby: 'Python',
                nameAgeStyle: {
                    fontSize: "20px",
                    color: "#0c8ac5"
                }
            },

            template: `<div>
                <div v-bind:style="nameAgeStyle">computed Mode rendering: {{nameAndAge}}</div>
                <div v-bind:style="nameAgeStyle">methods  Mode rendering: {{getNameAndAge()}}</div>
                <br>
                <input type="text" v-model="hobby">
                <div>hobby: {{hobby}}</div>
                <div>{{noUse()}}</div>
                </div>`,
            computed: {
                nameAndAge(){
                    console.log('call computed');
                    return `${this.name} ==> ${this.age}`;
                },

            },
            methods: {
                getNameAndAge() {
                    console.log('call methods');
                    return `${this.name} ==> ${this.age}`;
                },

                noUse(){
                    console.log("=methods==nouse==");
                }
            }
        })


    </script>

</body>
</html>

Tags: Vue Python

Posted on Sun, 05 Apr 2020 14:00:20 -0400 by Kadanis