Home >Web Front-end >Vue.js >Let's talk about computed properties in Vue
⭐⭐
computed is based on its dependency cache and will only be updated when its related dependencies change. The official documentation says this: For any complex logic that contains reactive data, you should use computed properties. (Learning video sharing: vue video tutorial)
⭐⭐
Splicing strings, Whether the score is passing or not, and the message records a piece of text, here it is implemented using computed
<div id="app"> <!-- 插值语法表达式直接进行拼接 --> <!-- 1.拼接姓名 --> <h2>{{fullname}}</h2> <!-- 2.显示分数及格或不及格 --> <h2>{{scorelevel}}</h2> <!-- 3.反转单词 --> <!-- reverse针对于数组,先用split转为数组,在用reverse --> <h2>{{reversetext}}</h2> </div> <script src="../lib/vue.js"></script> <script> const app = Vue.createApp({ data() { return { // name firstName: "kk", lastName: "cc", // score score: 99, // 文本中单词反转 message: "I love stydy Vue3", }; }, computed: { fullname() { return this.firstName + " " + this.lastName; }, scorelevel() { return this.score >= 60 ? "及格" : "不及格"; }, reversetext() { return this.message.split(" ").reverse().join(" "); }, }, }); app.mount("#app");
Of course we can also use Mustache interpolation syntax and methods, but for the processing of complex data, we often use computed. The writing method is clearer, and the calculated attributes are cached
⭐⭐
&tinsp;
So this is why we prefer computed
to use the same number of times when processing complex data When fullName is used, methods are executed three times and computed is executed once. This is because computed properties will be cached
##1.4. Setters and getters of computed properties
In most cases, computed properties only require one getter method, then the computed property value is For the function
computed: { // 语法糖 fullname() { return this.firstname + " " + this.lastname; }, // 完整写法 fullname: { get: function () { return this.firstname + " " + this.lastname; }, set: function (value) { const names = value.split(" "); this.firstname = names[0]; this.lastname = names[1]; }, },[Related video tutorial recommendation:
vuejs introductory tutorial、Getting started with web front-end】
The above is the detailed content of Let's talk about computed properties in Vue. For more information, please follow other related articles on the PHP Chinese website!