This article mainly introduces the detailed explanation of the difference between computed and methods in Vue. Now I will share it with you and give you a reference.
Computed in Vue can be used to simply splice the data that needs to be displayed
computed and methods
The task of splicing and displaying data is also It can be done with methods, but when the data on the page changes, the methods in methods will be called again (causing unnecessary performance consumption), and 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 It is called when the data changes, even if the changed data has nothing to do with itself
Test source code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>computed的使用</title> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script> </head> <body> <p id="root"> </p> <script> var vm = new Vue({ el: "#root", data: { name: "zhaozhao", age: 13, hobby: 'Python', nameAgeStyle: { fontSize: "20px", color: "#0c8ac5" } }, template: `<p> <p v-bind:style="nameAgeStyle">computed方式渲染: {{nameAndAge}}</p> <p v-bind:style="nameAgeStyle">methods 方式渲染: {{getNameAndAge()}}</p> <br> <input type="text" v-model="hobby"> <p>爱好: {{hobby}}</p> <p>{{noUse()}}</p> </p>`, computed: { nameAndAge: { get(){ console.log('调用computed'); return `${this.name} ==> ${this.age}`; } } }, methods: { getNameAndAge() { console.log('调用methods'); return `${this.name} ==> ${this.age}`; }, noUse(){ console.log("=methods==nouse=="); } } }) </script> </body> </html>
The above is what I compiled for everyone, I hope It will be helpful to everyone in the future.
Related articles:
Use js to realize the sample code of transmitting Json in the front and backend
JS gets url parameters, JS sends POST request method in json format
The above is the detailed content of Detailed explanation of the difference between computed and methods in Vue. For more information, please follow other related articles on the PHP Chinese website!