Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use watch in Vue3.0

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use watch in Vue3.0". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use watch in Vue3.0.

Using watch in Vue3.0

Watch is not a new concept in Vue3.0. When using Vue2.x, we often use watch to listen for changes in the evaluation result of an expression or a function on an Vue instance.

Review watch in Vue2.0

In Vue2.0, we can use watch to listen for changes in the evaluation results of expressions or functions on Vue instances in a number of ways, several of which are listed below

The most conventional mode of use

Export default {data () {return {name: 'Zijun', info: {gzh: 'some games at the front end'}, watch: {name (newValue, oldValue) {console.log (newValue, oldValue)}, 'info.gzh': {handler (newValue) OldValue) {console.log (newValue, oldValue)}, / / configure immediate to execute immediate: true}} immediately after watch

We can configure the properties above the Vue instance we want to listen to in the watch property, or through. The key path can be used to listen for the change of a property in the object. You can also configure immediate to trigger immediately after listening, and configure deep to deeply listen for the properties in the object, no matter how deep the nesting level is.

Use $watch snooping

In addition to the regular watch object writing, the $watch method is provided on the Vue instance, which gives you more flexibility to listen for changes to a property through $watch. For example, in a scenario where we have a form and then want to be able to listen for data changes in the form after the user modifies the form. However, there is a special scenario in which the backfill data of the form is requested asynchronously. In this case, we want to listen for changes after the data has been requested in the background, so we can use $watch. The following code is shown:

Export default {methods: {loadData () {fetch () .then (data = > {this.formData = data this.$watch ('formData', () = > {/ / callback function when the data changes) {deep: true})})}

Listening function expression

In addition to listening for a string, the first argument to $watch can also be a function that triggers a callback function when the return value of the function changes

This.$watch (() = > this.name, () = > {/ / the return value of the function changes, enter this callback function})

The above is some common writing methods we use watch in Vue2.0. For Vue3.0, because it is partially backward compatible with Vue2.0, the above usage can basically be used in Vue3.0, but a big highlight of Vue3.0 is composition API, so in addition to the writing method in Vue2.0, you can also use watch provided in componsition api.

Using watch in Vue3.0

In Vue3.0, in addition to the way Vue2.0 is written, there are two api that can listen for data changes, the first is watch, and the second is watchEffect. For watch, it is basically the same as the use of $watch in Vue2.0, and watchEffect is the new api provided by Vue3.0

The usage of watch

The following example shows how to use watch

Import {watch, ref, reactive} from 'vue'export default {setup () {const name = ref (' Zijun') const otherName = reactive ({firstName: 'king', lastName: 'two dogs'}) watch (name, (newValue, oldValue) = > {/ / output player console.log (newValue) at the front end OldValue)}) / / watch can listen on the return value of a function watch (() = > {return otherName.firstName + otherName.lastName}, value = > {/ / when the firstName or lastName in otherName changes Will enter this function console.log (`my name is ${value} `) setTimeout (() = > {name.value = 'otherName.firstName =' Li'}, 3000)}

In addition to listening to a single value or function return value, watch can also listen to multiple data sources at the same time, as shown in the following code:

Export default {setup () {const name = ref ('Zijun') const gzh = ref ('play at the front end') watch ([name, gzh], ([name, gzh], [prevName, prevGzh]) = > {console.log (prevName, name) console.log (prevGzh, gzh)} setTimeout () = > {name.value = 'play at the front end' gzh.value = 'follow me Play with the front end'}, 3000)}} watchEffect usage

The usage of watchEffect is different from that of watch. WatchEffect passes in a function and then executes it immediately. It listens for responsive dependencies in the function, and then reinvokes the passed function when the dependency changes, as shown in the following code:

Import {ref, watchEffect} from 'vue'export default {setup () {const id = ref (' 0') watchEffect (() = > {/ / output 0 and then output 1 console.log (id.value)}) setTimeout (() = > {id.value ='1'}, 2000)}}

Stop execution

$watch in Vue2.0 returns a function when called, and executes this function to stop watch, as shown in the following code

Const unwatch = this.$watch ('name', () = > {}) / / stop listening after two seconds setTimeout (() = > {unwatch ()}, 2000)

In Vue3.0, watch and watchEffect also return a unwatch function to cancel execution, as shown in the following code

Export default {setup () {const id = ref ('0') const unwatch = watchEffect (() = > {/ / just output 0 console.log (id.value)}) setTimeout (() = > {id.value ='1'}, 2000) / / cancel watch after 1 second So the above code will only output 0 setTimeout (() = > {unwatch ()}, 1000)}}

Removal of side effects

Imagine a scenario where there are two drop-down boxes on the interface, and the data of the second drop-down box is linked according to the data of the first drop-down box. When the data of the first drop-down box changes, the data of the second drop-down box will be obtained by sending a network request. At this point, we can implement this function through watchEffect, such as the following code

Import {ref, watchEffect} from 'vue' function loadData (id) {return new Promise (resolve = > {setTimeout (()) = > {resolve (new Array (10) .fill (0). Map (() = > {return id.value + Math.random ()}))} 2000)})} export default {setup () {/ / data selected in drop-down box 1 const select1Id = ref (0) / / data in drop-down box 2 const select2List = ref ([]) watchEffect (() = > {/ / Simulation request loadData (select1Id) .then (data = > {select2List.value = data console.log (data)})}) / / simulated data changes setInterval (() = > {select1Id.value = 1}) 3000)}}

Now, if I switch the data of the first drop-down box and the data request has been sent, then I switch the page to another page, because the request has been made, so I hope that when the page leaves, I can end the request to prevent an exception after the data is returned. At this time, you can use the input parameter passed in by watchEffect for the first callback function to handle this situation, as shown in the following code

Function loadData (id, cb) {return new Promise (resolve = > {const timer = setTimeout (()) = > {resolve (new Array (10) .fill (0) .map (() = > {return id.value + Math.random ()}))} 2000) cb (() = > {clearTimeout (timer)} export default {setup () {/ / data selected in drop-down box 1 const select1Id = ref (0) / / data in drop-down box 2 const select2List = ref ([]) watchEffect (onInvalidate = > {/ / Simulation request let cancel = undefined / / the first parameter is a callback function Used to simulate a cancellation request, about a cancellation request You can learn about axios's CancelToken loadData (select1Id) Cb = > {cancel = cb}) .then (data = > {select2List.value = data console.log (data)}) onInvalidate (() = > {cancel & & cancel ()}} Vue3.0 using calculation properties

Think about what we usually do with computational properties in Vue2.0. I think the most common thing is that when there is a complex calculation in the template, you can use the calculation attribute first, and then use it in the template. In fact, the calculation attribute in Vue3.0 plays the same role as Vue2.0.

Using calculation properties in Vue2.0

Computed: {getName () {const {firstName, lastName} = this.info return firstName + lastName}}

Using calculation properties in Vue3.0

{{name}} import {computed, reactive} from 'vue' export default {setup () {const info = reactive ({firstName:' Wang', lastName:'er Dog'}) const name = computed (() = > info.firstName + info.lastName) return {name}

Like Vue2.0, the calculation property of Vue3.0 can also be set to getter and setter. For example, in the calculation property in the above code, only getter is set, that is, if the parameter passed in by adding cumputed is a function, then this is getter. If you want to set setter, you need to write as follows

Export default {setup () {const info = reactive ({firstName: 'Wang', lastName: 'two dogs'}) const name = computed ({get: () = > info.firstName +'-'+ info.lastName) Set (val) {const names = val.split ('-') info.firstName = names [0] info.lastName = names [1]}) return {name}} Vue3.0 initializes vue-router with vue-router

When we use vue-router in Vue2.0, we implement a VueRouter instance through new VueRouter, as in the following code

Import Vue from 'vue'import VueRouter from' vue-router'Vue.use (VueRouter) const router = new VueRouter ({mode: 'history', routes: []}) export default router

But when it comes to Vue3.0, we create an instance of VueRouter that changes a little bit, just as Vue3.0 needs to initialize a Vue instance in main.js like the following

Import {createApp} from 'vue'createApp (App). $mount (' # app')

Vue-router has also modified the way this function is declared

Import {createRouter, createWebHashHistory} from 'vue-router'const router = createRouter ({/ / vue-router has two route modes: hash and history. You can specify history: createWebHashHistory (), routes}) router.beforeEach (() = > {}) router.afterEach (() = > {}) export default router through createWebHashHistory and createWebHistory

Then in main.js, through the

CreateApp (App) .use (router)

To reference into Vue

Using vue-router in setup

In Vue2.0, we can get the current route through this.$route, and then get the route instance through this.$router to jump the route, but in setup, we can't get this, which means we can't use vue-router like Vue2.0, so we need to use it like this

Import {useRoute, useRouter} from 'vue-router'export default {setup () {/ / get the current route const route = useRoute () / / get the route instance const router = useRouter () / / when the current route changes Call callback function watch (() = > route, () = > {/ / callback function}, {immediate: true, deep: true}) / / Route Jump function getHome () {router.push ({path:'/ home'})} return {getHome ()}}

In the above code, we use watch to listen for route changes. In addition to watch, we can also use the lifecycle function provided by vue-router.

Import {onBeforeRouteUpdate, useRoute} from 'vue-router'export default {setup () {onBeforeRouteUpdate (()) = > {/ / call callback function} when the current route changes)}}

In addition to onBeforeRouteUpdate, vue-router also provides a lifecycle hook function when the route leaves

OnBeforeRouteLeave (() = > {console.log ('called when the current page route leaves')}) use vuex in Vue3.0

In fact, the use of vuex in Vue3.0 is basically the same as that of vue-router.

Initialize vuex

First create a new store/index.js, and then add the following code

Import {createStore} from 'vuex'export default createStore ({state: {}, mutations: {}, actions: {}})

Then in main.js, use the following ways

CreateApp (App) .use (store) uses vuex in setup

Like useRouter, vuex also provides useStore for use when calling, such as the following code

Import router from'@ / router'import store from'@ / store'router.beforeEach (async (to, from, next) = > {if (to.path! = ='/ login' & & store.getters ['permission/getRoleMenus']. Length = = 0) {await store.dispatch (' permission/loadRoleMenus') next ()} else {next ()})

The rest of the usage is basically the same as that in Vue2.0. You can refer to the vuex official documentation for details.

Life cycle Hook function in Vue3.0

In the previous article, we said that Vue3.0 is compatible with part of Vue2.0, so for the component writing of Vue2.0, the lifecycle hook function has not changed, but if you are using componsition api, then you need to make some adjustments

Cancel beforeCreate and created

When using componsition api, setup actually replaces beforeCreate and created, because setup is the actual entry function of the component.

BeforeDestroy and destroyed changed their names.

In setup, beforeDestroy is renamed to onBeforeUnmount,destroyed and renamed to onUnmounted

Change the lifecycle function name to on+XXX, for example, mounted becomes onMounted,updated and becomes onUpdated.

How to use lifecycle functions in setup

Setup () {onMounted (() = > {console.log ('mountedstones')}) onUpdated (() = > {console.log ('updatedstones')}) onUnmounted (() = > {console.log ('unmountedstones')})}

The actual usage is basically the same as that of Vue2.0, but the writing method has changed, so the learning cost is very low.

Thank you for your reading, the above is the content of "how to use watch in Vue3.0", after the study of this article, I believe you have a deeper understanding of how to use watch in Vue3.0, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report