The expression syntax of Vue template only supports a single expression for simple operations; for complex logical calculations, calculated properties should be used computed.
Computed can rely on (calculate) the data of props, data, and vuex, that is, you can declare a calculated attribute to respond to data changes in props/data/vuex and return a result that has undergone some calculation. [Related recommendations: vue.js video tutorial]
How to write calculated attributes
The attribute value of the computed attribute can be a function or object
1. The attribute value is function. At this time, the calculated attribute only has getter
<div id="app"> {{fullName}} </div> <script> let vm = new Vue({ el: '#app', data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName () { return this.firstName + ' ' + this.lastName } } }) </script>
2. The attribute value is an object
When the computed attribute value is an object, the object's attribute attribute can be configured with the get and set methods, through This approach provides a setter for a computed property.
fullName: { get () { return this.firstName + ' ' + this.lastName }, set (newValue) { const names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } }
Computed property supportCache
When the view changes but the data on which the calculated property depends does not change , the value will be retrieved directly from the cache.
In the following example, the calculated property messageLength and the method getMessageLength implement the same function. When updating the view by clicking the button, you will find that the method getMessageLength will be executed. Obviously in this case, using the calculated property is more performant than the method. good.
<div id="app"> {{messageLength}}-{{getMessageLength()}} <button @click="onClick">点击{{i}}</button> </div> <script> let vm = new Vue({ el: '#app', data: { message: 'Hello world', i: 0 }, computed: { messageLength () { console.log('messageLength执行了') return this.message.length } }, methods: { getMessageLength () { console.log('getMessageLength执行了') return this.message.length }, onClick () { this.i++ } } }) </script>
Computed property parameters passing
In a Vue instance, calculated properties exist as properties. If you want to pass parameters, you need to use a closure to change the property value to a function
computed: { fullName () { return function (maxLength) { return (this.firstName + ' ' + this.lastName).substring(0, maxLength) } }}
In this case, using a computed property is equivalent to using a method.
Computed property and watch property
Computed properties can respond to data changes on the Vue instance, and watch properties can also observe and respond to data changes on the Vue instance.
Watch can monitor data changes in props, data and computed, and execute a function.
When used:
computed is used for calculation. It requires a result to be returned. There is no need to add parentheses when calling. It will automatically cache based on one or more dependencies
. If the dependency No change, computed will not automatically calculate;
watch is used for monitoring, and can only monitor one data at a time
. If the monitored data changes, execute the function. It has two options:
- immediate indicates whether to execute this function when the component is rendered for the first time. The default is false.
- deep means monitoring changes in the internal attributes of an object, and the default is false.
Implementing asynchronous calculation
1. The computed attribute cannot return the result of an asynchronous operation, but You can rely on the data in Vuex, so you can get the result of the asynchronous operation by returning store.state
2. Asynchronous calculation of attributes can be implemented through the vue-async-computed plug-in. The list attribute will be assigned a Promise, obviously Not the result we need
import Vue from 'vue'import AsyncComputed from 'vue-async-computed'import axios from 'axios'Vue.use(AsyncComputed)export default { name: 'MediaIndex', data () { return { pageNo: 1 } }, computed: { list () { return axios(`https://www.fastmock.site/mock/d6b39fde63cbe98a4f2fb92ff5b25a6d/api/products?pageNo=${this.pageNo}`) .then(res => res.data) } }, asyncComputed: { asyncList () { return axios(`https://www.fastmock.site/mock/d6b39fde63cbe98a4f2fb92ff5b25a6d/api/products?pageNo=${this.pageNo}`) .then(res => res.data) } }}
vue-async-computed
Skillfully use computed properties to calculate props
The following example implements props Two-way binding
export default { name: 'Pagination', props: { page: { type: Number, default: 1 }, limit: { type: Number, default: 10 } }, computed: { currentPage: { get() { return this.page }, set(val) { this.$emit('update:page', val) } }, pageSize: { get() { return this.limit }, set(val) { this.$emit('update:limit', val) } } }
The above is the detailed content of In-depth analysis of Vue's computed property API (computed). For more information, please follow other related articles on the PHP Chinese website!

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
