Home >Web Front-end >JS Tutorial >Knowledge points gained using Vue3.0 (2)
# I work overtime every day and I am busy every day, and the demand comes like a tiger or a wolf. The test questions piled up like a mountain, and I returned home disappointed.
Related learning recommendations: javascript
Recently, I have been studying Vue3.0
related knowledge after work , although Vue3.0
is still the rc
version, this does not affect our study. Today's article is my fourth article about Vue3.0
. In the previous article, we explained how to build the Vue3.0
development environment through vite
and vuecli
, and then introduced the Vue3.0
setup
,reactive
,ref
, etc. Today’s article mainly explains the following content:
Vue3.0
Used in watch
Vue3.0
Used in computed properties Vue3.0
Used in vue-router
Used in Vue3.0
vuex
Before starting this article, the editor provides A Vue3.0
development environment has been created. The warehouse address is gitee.com/f_zijun/vue…. Welcome to use it. This article was first published on the public account [Front-end Youdewan], which is a public account focusing on Vue
and Interview
. To improve your market competitiveness, just in [Front-end Youde] Play】. At the same time, click the following link to access the editor's other related articles about Vue3.0
To learn Vue3.0, let's first learn about Proxy
Usagevite
Build a Vue3.0
learning environment
Knowledge points gained using Vue3.0 (1)
watch
in #Vue3.0 is not a new concept in
Vue3.0. When using # When ##Vue2.x
, we often use watch
to monitor changes in an expression or a function calculation result on the Vue
instance. Review
In Vue2.0
, we use You can monitor changes in expressions or function calculation results on the Vue
instance through the following multiple methods. The following is a list of several of themThe most common Usage
export default { data() { return { name: '子君', info: { gzh: '前端有的玩' } } }, watch: { name(newValue, oldValue) { console.log(newValue, oldValue) }, 'info.gzh': { handler(newValue, oldValue) { console.log(newValue, oldValue) }, // 配置immediate会在watch之后立即执行 immediate: true } } }复制代码
instance to be monitored in the
watch property, or we can go through the .
key path Monitoring changes in a certain attribute in the object can also be triggered immediately after monitoring by configuring immediate
, and configuring deep
to deeply monitor the properties in the object, no matter how deep the nesting level is. . Use
In addition to the conventional watch
object writing method,
The $watch
method is provided on the instance, which can be used to more flexibly monitor changes in a certain attribute. For example, in this scenario, we have a form, and we hope to monitor the data changes in the form after the user modifies the form. But there is a special scenario, that is, the backfill data of the form is requested asynchronously. At this time, we hope to monitor the changes after requesting the data in the background. In this case, we can use $watch
. As shown in the following code: <pre class="brush:js;toolbar:false;">export default { methods: {
loadData() {
fetch().then(data => { this.formData = data this.$watch( &#39;formData&#39;,
() => { // formData数据发生变化后会进入此回调函数
},
{ deep: true
}
)
})
}
}
}复制代码</pre>
Listening function expression
In addition to the listening string, the first parameter of
this.$watch(() => this.name, () => { // 函数的返回值发生变化,进入此回调函数})复制代码
The above are some common writing methods we use
watch in Vue2.0
, For
, 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 the composition API
, so in addition to the writing method in Vue2.0
, you can also use componsition
watch provided in api
is used in Vue3.0
Vue3.0
, in addition to the writing method of Vue2.0
, there are two that can monitor data changes. The first one iswatch
, the second one is watchEffect
. For watch
, its usage is basically the same as $watch
in Vue2.0
, while watchEffect
is Vue3. 0
Newly providedapi
Usage of watch
The following example demonstrates how to use
watch
import { watch, ref, reactive } from 'vue'export default { setup() { const name = ref('子君') const otherName = reactive({ firstName: '王', lastName: '二狗' }) watch(name, (newValue, oldValue) => { // 输出 前端有的玩 子君 console.log(newValue, oldValue) }) // watch 可以监听一个函数的返回值 watch( () => { return otherName.firstName + otherName.lastName }, value => { // 当otherName中的 firstName或者lastName发生变化时,都会进入这个函数 console.log(`我叫${value}`) } ) setTimeout(() => { name.value = '前端有的玩' otherName.firstName = '李' }, 3000) } }复制代码
In addition to monitoring a single value or function return value, you can also monitor multiple data sources at the same time, as shown in the following code:<pre class="brush:js;toolbar:false;">export default {
setup() { const name = ref(&#39;子君&#39;) const gzh = ref(&#39;前端有的玩&#39;)
watch([name, gzh], ([name, gzh], [prevName, prevGzh]) => { console.log(prevName, name) console.log(prevGzh, gzh)
})
setTimeout(() => {
name.value = &#39;前端有的玩&#39;
gzh.value = &#39;关注我,一起玩前端&#39;
}, 3000)
}
}复制代码</pre><h5 data-id="heading-4">watchEffect的用法</h5>
<p><code>watchEffect
的用法与watch
有所不同,watchEffect
会传入一个函数,然后立即执行这个函数,对于函数里面的响应式依赖会进行监听,然后当依赖发生变化时,会重新调用传入的函数,如下代码所示:
import { ref, watchEffect } from 'vue'export default { setup() { const id = ref('0') watchEffect(() => { // 先输出 0 然后两秒后输出 1 console.log(id.value) }) setTimeout(() => { id.value = '1' }, 2000) } }复制代码
停止执行
Vue2.0
中的$watch
会在调用的时候返回一个函数,执行这个函数可以停止watch
,如下代码所示
const unwatch = this.$watch('name',() => {})// 两秒后停止监听setTimeout(()=> { unwatch() }, 2000)复制代码
在Vue3.0
中,watch
与watchEffect
同样也会返回一个unwatch
函数,用于取消执行,比如下面代码所示
export default { setup() { const id = ref('0') const unwatch = watchEffect(() => { // 仅仅输出0 console.log(id.value) }) setTimeout(() => { id.value = '1' }, 2000) // 1秒后取消watch,所以上面的代码只会输出0 setTimeout(() => { unwatch() }, 1000) } }复制代码
清除副作用
想象一下这样的一个场景,界面上面有两个下拉框,第二个下拉框的数据是根据第一个下拉框的数据联动的,当第一个下拉框数据发生变化后,第二个下拉框的数据会通过发送一个网络请求进行获取。这时候我们可以通过watchEffect
来实现这个功能,比如像下面代码这样
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() { // 下拉框1 选中的数据 const select1Id = ref(0) // 下拉框2的数据 const select2List = ref([]) watchEffect(() => { // 模拟请求 loadData(select1Id).then(data => { select2List.value = data console.log(data) }) }) // 模拟数据发生变化 setInterval(() => { select1Id.value = 1 }, 3000) } }复制代码
现在假如我切换了一下第一个下拉框的数据之后,这时候数据请求已经发出,然后我将这个页面切换到另一个页面,因为请求已经发出,所以我希望在页面离开的时候,可以结束这个请求,防止数据返回后出现异常,这时候就可以使用watchEffect
为第一个回调函数传入的入参来处理这个情况,如下代码所示
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() { // 下拉框1 选中的数据 const select1Id = ref(0) // 下拉框2的数据 const select2List = ref([]) watchEffect(onInvalidate => { // 模拟请求 let cancel = undefined // 第一个参数是一个回调函数,用于模拟取消请求,关于取消请求,可以了解axios的CancelToken loadData(select1Id, cb => { cancel = cb }).then(data => { select2List.value = data console.log(data) }) onInvalidate(() => { cancel && cancel() }) }) } }复制代码
Vue3.0
中使用计算属性想一想在Vue2.0
中我们一般会用计算属性做什么操作呢?我想最常见的就是当模板中有一个复杂计算的时候,可以先使用计算属性进行计算,然后再在模板中使用,实际上,Vue3.0
中的计算属性的作用和Vue2.0
的作用基本是一样的。
在Vue2.0
中使用计算属性
computed: { getName() { const { firstName, lastName } = this.info return firstName + lastName } },复制代码
在Vue3.0
中使用计算属性
<template> <p class="about"> <h1>{{ name }}</h1> </p></template> <script> import { computed, reactive } from 'vue' export default { setup() { const info = reactive({ firstName: '王', lastName: '二狗' }) const name = computed(() => info.firstName + info.lastName) return { name } } } </script>复制代码
和Vue2.0
一样,Vue3.0
的计算属性也可以设置getter
和setter
,比如上面代码中的计算属性,只设置了getter
,即加入cumputed
传入的参数是一个函数,那么这个就是getter
,假如要设置setter
,需要像下面这样去写
export default { setup() { const info = reactive({ firstName: '王', lastName: '二狗' }) 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
中使用vue-router
vue-router
在Vue2.0
中我们使用vue-router
的时候,会通过new VueRouter
的方式去实现一个VueRouter
实例,就像下面代码这样
import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)const router = new VueRouter({ mode: 'history', routes: [] })export default router复制代码
但到了Vue3.0
,我们创建VueRouter
的实例发生了一点点变化,就像Vue3.0
在main.js
中初始化Vue
实例需要像下面写法一样
import { createApp } from 'vue'createApp(App).$mount('#app')复制代码
vue-router
也修改为了这种函数的声明方式
import { createRouter, createWebHashHistory } from 'vue-router'const router = createRouter({ // vue-router有hash和history两种路由模式,可以通过createWebHashHistory和createWebHistory来指定 history: createWebHashHistory(), routes }) router.beforeEach(() => { }) router.afterEach(() => { })export default router复制代码
然后在main.js
中,通过
createApp(App).use(router)复制代码
来引用到Vue
中
setup
中使用vue-router
在Vue2.0
中,我们通过this.$route
可以获取到当前的路由,然后通过this.$router
来获取到路由实例来进行路由跳转,但是在setup
中,我们是无法拿到this
的,这也意味着我们不能像Vue2.0
那样去使用vue-router
, 此时就需要像下面这样去使用
import { useRoute, useRouter } from 'vue-router'export default { setup() { // 获取当前路由 const route = useRoute() // 获取路由实例 const router = useRouter() // 当当前路由发生变化时,调用回调函数 watch(() => route, () => { // 回调函数 }, { immediate: true, deep: true }) // 路由跳转 function getHome() { router.push({ path: '/home' }) } return { getHome() } } }复制代码
上面代码我们使用watch
来监听路由是否发生变化,除了watch
之外,我们也可以使用vue-router
提供的生命周期函数
import { onBeforeRouteUpdate, useRoute } from 'vue-router'export default { setup() { onBeforeRouteUpdate(() => { // 当当前路由发生变化时,调用回调函数 }) } }复制代码
除了onBeforeRouteUpdate
之外,vue-router
在路由离开的时候也提供了一个生命周期钩子函数
onBeforeRouteLeave(() => { console.log('当当前页面路由离开的时候调用') })复制代码
Vue3.0
中使用vuex
其实vuex
在Vue3.0
中的使用方式和vue-router
基本是一致的
vuex
首先新建store/index.js
,然后添加如下代码
import { createStore } from 'vuex'export default createStore({ state: {}, mutations: {}, actions: {} })复制代码
然后在main.js
中,通过以下方式使用
createApp(App).use(store)复制代码
setup
中使用vuex
和useRouter
一样,vuex
也提供了useStore
供调用时使用,比如下面这段代码
import { useStore } from 'vuex'export default { setup() { const store = useStore() const roleMenus = store.getters['roleMenus'] return { roleMenus } } }复制代码
其余的使用方式基本和Vue2.0
中的用法是一致的,大家具体可以参考vuex
官方文档
在前文中,我们说到Vue3.0
是兼容一部分Vue2.0
的,所以对于Vue2.0
的组件写法,生命周期钩子函数并未发生变化,但是假如你使用的是componsition api
,那么就需要做一部分调整
取消beforeCreate
与created
在使用componsition api
的时候,其实setup
就代替了beforeCreate
与created
,因为setup
就是组件的实际入口函数。
beforeDestroy
与destroyed
改名了
在setup
中,beforeDestroy
更名为onBeforeUnmount
,destroyed
更名为onUnmounted
将生命周期函数名称变为on+XXX
,比如mounted
变成了onMounted
,updated
变成了onUpdated
在setup
中使用生命周期函数的方式
setup() { onMounted(() => { console.log('mounted!') }) onUpdated(() => { console.log('updated!') }) onUnmounted(() => { console.log('unmounted!') }) }复制代码
实际用法与Vue2.0
基本是一致的,只是写法发生了变化,所以学习成本是很低的。
这是小编关于Vue3.0
的第四篇文章,每一篇文章都是自己在学习中做的一些总结。小编整理了一个vue3.0
的开发环境,仓库地址为 gitee.com/f_zijun/vue…,内部集成了typescript
,eslint
,vue-router
,vuex
,ant desigin vue
等,希望可以帮到正在学习Vue3.0
的你,同时关注公众号【前端有的玩】,带给你不一样的惊喜。喜欢本文,可以给小编一个赞哦。
不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶。 ——文森特・梵高
The above is the detailed content of Knowledge points gained using Vue3.0 (2). For more information, please follow other related articles on the PHP Chinese website!