


Detailed explanation of setup syntax sugar, computed function, and watch function in Vue3
This article will help you learn Vue3 and understand the setup syntax sugar, computed function, and watch function in Vue3. I hope it will be helpful to you!
setup syntax sugar
Have you noticed that in our previous articles? In the case code, there are some similar codes in the template of each case. These codes are our setup function, but as the entry function of the combined API, all our combined APIs must be written in it. Do we have to write it every time? Do you want to write this thing? In fact, Vue provides syntactic sugar for setup. Does everyone know what syntactic sugar is? [Related recommendations: vuejs video tutorial, web front-end development]
For example, v-model in our Vue2 is just syntactic sugar. You can pass such a command Saves a lot of two-way data binding code! Then let’s take a look at how our setup can be simplified. Taking the following code as an example, we declare a function and click a button to trigger a simple effect such as printing hi;
<template> <div> <button @click="hello">hello</button> </div> </template> <script> export default { setup() { const hello = () => { console.log('hi') } return { hello } } } </script>
<template> <div> <button @click="hello">hello</button> </div> </template> <script setup> const hello = () => { console.log('hi') } </script>
The above is what we use The code effect after the setup syntax sugar is the same in functional implementation; in the script setup tag, all data and functions can be used directly in the template! You can give it a try. You can modify the examples in our Vue3 Transparency Tutorial [4] article using setup syntax sugar!
The top-level variables in script setup can be used directly in the template
computed function
In the last article, we learned two combined APIs, namely ref and reactive. Now we are learning the computed function. I believe everyone must know that it is our calculated data definition function. Before, it was the computed option. Now comes the computed function; let’s experience it through a small case! Use of computed functions: In fact, under what circumstances will we use computed properties? It must be to obtain new data through dependent data!
1) Introduce computed from Vue
2) Use it in setup, use a function, the return value of the function is the calculated data
3) Finally, return it through setup, template Use it. If you use setup syntax sugar, this step is not needed.
We can give a simple example. For example, if we define a score number, pure score information, then we use the computed function to calculate it for us. More than 60 passing results were obtained; we directly used the script setup method to code!
<template> <div> <p>成绩单</p> <a v-for="num in achievement"> {{ num }} / </a> <p>及格成绩单</p> <a v-for="num in passList"> {{ num }} / </a> </div> </template> <script setup> import { computed, ref } from 'vue'; const achievement = ref([44, 22, 66, 77, 99, 88, 70, 21]) const passList = computed(() => { return achievement.value.filter(item => item > 60) }) </script>
watch function
Like the computed function, the watch function is also a part of the combined API Member, watch is actually a function that monitors data changes, so what are its uses in Vue3? You can use watch to monitor one or more responsive data, you can use watch to monitor an attribute in the responsive data (simple data or complex data), you can configure deep monitoring, or you can use watch monitoring to implement default execution; let's try the code separately. How to write
Monitoring a data through watch
##watcha monitors a data, the function has two parameters: the first one to be monitored Data, the second parameter is the callback function triggered after the monitoring value changes. The callback function also has two parameters: new value and old value<template> <div> 总赞数:{{ num }} <button @click="num++">点赞</button> </div> </template> <script setup> import { ref, watch } from 'vue'; //创建一个响应式数据,我们通过点赞按钮改变num的值 const num = ref(0) watch(num, (nv, ov) => { console.log(nv, ov) }) </script>
Monitor multiple data through watch
##watcha monitors multiple data. For example, below we need to monitor changes in num and user objects. The function has two parameters: A data to be monitored (an array is used because it is multiple data), and the second parameter is a callback function that is triggered when the monitoring value changes.<template> <div> 总赞数:{{ num }} <button @click="num++">点赞</button> </div> <p>姓名:{{ user.name }}</p> <p>年龄:{{ user.age }}</p> <button @click="user.age++">过年啦</button> </template> <script setup> import { ref, watch, reactive } from 'vue'; const num = ref(0) let user = reactive( { name: "几何心凉", age: 18 } ) watch([num, user], () => { console.log('我监听到了') }) </script>
Listen to a property of the object through watch (simple type)
watch monitors an attribute of the object and it is a simple type of attribute. For example, if we monitor the age value in the user below, which is a simple type, then the first parameter form of our watch needs to be a function that uses the object attribute as the return value. ;The second parameter is the changed callback function.<template> <p>姓名:{{ user.name }}</p> <p>年龄:{{ user.age }}</p> <button @click="user.age++">过年啦</button> </template> <script setup> import { ref, watch, reactive } from 'vue'; let user = reactive( { name: "几何心凉", age: 18 } ) watch(()=>user.age, () => { console.log('我监听到了user.age的变化') }) </script>
Listen to a property of the object through watch (complex type) watch监听对象的一个属性并且是复杂类型的属性,比如下面的我们要监听user中的info,我们尝试一下改变user中info中的wages值,那我们watch的第一个参数形式需要是将对象属性作为返回值的函数;第二个参数是改变后的回调函数。这时候还需要第三个参数那就是 deep 开启深度监听 通过watch监听数据默认执行 其实这种情况并不多但是也会遇到这种情况,就是我们在监听数据变化的时候,先默认执行一次;其实就是添加我们的immediate参数为true,我们以最初的num为例哈! 掌握了setup语法糖,我们编码更便捷,并且带领大家掌握 computed、watch 函数的使用,希望大家能够自己实现上面的案例功能哦,做到真正的掌握这些点!下一篇文章中我们将带领大家学习Vue3的生命周期,拭目以待吧!各位小伙伴让我们 let’s coding!<template>
<p>姓名:{{ user.name }}</p>
<p>年龄:{{ user.age }}</p>
<p>薪资:{{ user.info.wages }}</p>
<button @click="user.age++">过年啦</button>
<button @click="user.info.wages+=2000">加薪了</button>
</template>
<script setup>
import { ref, watch, reactive } from 'vue';
let user = reactive(
{
name: "几何心凉",
age: 18,
info:{
wages:20000
}
}
)
watch(()=>user.info, () => {
console.log('我监听到了user.info的变化')
},{
deep:true
})
</script>
<template>
<div>
总赞数:{{ num }} <button @click="num++">点赞</button>
</div>
</template>
<script setup>
import { ref, watch, reactive } from 'vue';
const num = ref(0)
watch(num, () => {
console.log('我打印了')
},{
immediate:true
})
</script>
写在最后
The above is the detailed content of Detailed explanation of setup syntax sugar, computed function, and watch function in Vue3. 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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.
