# 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 inwatch
-
Vue3.0
Used in computed properties -
Vue3.0
Used invue-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)
## The use of watch
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
watchYou 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 } } }复制代码
- We can configure the properties on the
- Vue
instance to be monitored in the
watchproperty, or we can go through the
$watch.
key path Monitoring changes in a certain attribute in the object can also be triggered immediately after monitoring by configuringimmediate
, and configuringdeep
to deeply monitor the properties in the object, no matter how deep the nesting level is. .Use
to monitor -
In addition to the conventional
Vuewatch
object writing method,The
$watch$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:php;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
can also be It is a function. When the return value of the function changes, the callback function is triggered this.$watch(() => this.name, () => { // 函数的返回值发生变化,进入此回调函数})复制代码
The above are some common writing methods we use
watchin
Vue3.0Vue2.0
, For, because it is partially backward compatible with
watchVue2.0
, the above usage can basically be used inVue3.0
, but a big highlight ofVue3.0
is thecomposition API
, so in addition to the writing method inVue2.0
, you can also usecomponsition
watchprovided in api
is used inVue3.0
In Vue3.0
, in addition to the writing method of Vue2.0
, there are two
api 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) } }复制代码
watch
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:php;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 id="watchEffect的用法">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 id="nbsp-name-nbsp">{{ 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中的生命周期钩子函数
在前文中,我们说到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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools