Home>Article> 15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

青灯夜游
青灯夜游 forward
2022-10-21 20:24:28 3633browse

This article will share with you some common problems in the development of Vue3 family bucket, so that you can avoid pitfalls and minefields. I hope it can help you!

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

I recently got started with Vue3 and completed 3 projects. I encountered a lot of problems. Today I will take some time to sort them out and share with you 15 of the more common problems. Basically Corresponding document addresses are posted, please read more documents ~ The three completed projects are basically developed using Vue3 (setup-script mode) Family Bucket, so they are mainly summarized in several aspects:

  • Vue3
  • Vite
  • VueRouter
  • Pinia
  • ElementPlus

(Learning video sharing:vue video tutorial)

1. Vue3

1. Changes in the life cycle methods of Vue2.x and Vue3.x

Document address: https://v3.cn.vuejs.org/guide/composition-api-lifecycle-hooks.html

Vue2.x and Vue3.x life cycle methods The changes are quite big, let’s take a look first:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

Currently Vue3.x still supports the life cycle of Vue2.x, but it is not recommended to mix and match. You can use 2.x in the early stage. life cycle, try to use the 3.x life cycle development later.

Since I use thescript-srtupmode, I directly use the life cycle function of Vue3.x:

// A.vue\ 

The execution timing of each hook, You can also take a look at the documentation:v3.cn.vuejs.org/guide/insta…

2. The parent component in script-setup mode obtains the data of the child component

Document address:v3.cn.vuejs.org/api/sfc-scr…

Here we mainly introduce how the parent component obtains the child For variables defined within the component, regarding parent-child component communication, you can read the documentation for more details:v3.cn.vuejs.org/guide/compo…

We can useglobal compilation ThedefineExposemacro of the tool macroexposes the parameters in the child component to the parent component and uses the{key: vlaue}method as a parameter. The parent component passes the template If you obtain the subcomponent instance using the ref method, you can obtain the corresponding value:

// 子组件\ \ \ // 父组件\ \ 

Note:

  • Global compiler macros can only be used in script- Used in setup mode; in
  • script-setup mode, macros can be used directly withoutimport;
  • script-setup mode provides a total of 4 Macros, including: defineProps, defineEmits, defineExpose, withDefaults.

3. Provide default values for props

definedProps Documentation:v3.cn.vuejs.org/api/sfc-scr …Document:v3.cn.vuejs.org/api/sfc-scr…

The fourglobal compilations provided by script-setup mode were introduced earlier Device macrohas not been introduced in detail yet. This section introducesdefinePropsandwithDefaults. ThedefinePropsmacro can be used to define the input parameters of the component, as follows:

Only define theschemaand # in thepropsattribute here. ##modelValueTwo attribute types,definePropsThe shortcoming of this declaration is that it does not provide a way to set the default value of props.

In fact, we can achieve this through the withDefaults macro:

withDefaults The auxiliary function provides type checking for default values and ensures that the type of returned props deletes the declared default Optional flag for the value attribute.

4. Configure global custom parameters

Document address:

v3.cn.vuejs.org/guide/migra…

在 Vue2.x 中我们可以通过Vue.prototype添加全局属性 property。但是在 Vue3.x 中需要将Vue.prototype替换为config.globalProperties配置:

// Vue2.x\ Vue.prototype.$api = axios;\ Vue.prototype.$eventBus = eventBus;\ \ // Vue3.x\ const app = createApp({})\ app.config.globalProperties.$api = axios;\ app.config.globalProperties.$eventBus = eventBus;

使用时需要先通过 vue 提供的getCurrentInstance方法获取实例对象:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

5. v-model 变化

文档地址:v3.cn.vuejs.org/guide/migra…

当我们在使用v-model指令的时候,实际上v-bindv-on组合的简写,Vue2.x 和 Vue3.x 又存在差异。

Vue2.x

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

在子组件中,如果要对某一个属性进行双向数据绑定,只要通过this.$emit('update:myPropName', newValue)就能更新其v-model绑定的值。

  • Vue3.x

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

script-setup模式下就不能使用this.$emit去派发更新事件,毕竟没有this,这时候需要使用前面有介绍到的 defineProps、defineEmits 两个宏来实现:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

父组件使用的时候就很简单:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

6. 开发环境报错不好排查

文档地址:v3.cn.vuejs.org/api/applica…

Vue3.x 对于一些开发过程中的异常,做了更友好的提示警告,比如下面这个提示:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

这样能够更清楚的告知异常的出处,可以看出大概是这边的问题,但还不够清楚。这时候就可以添加 Vue3.x 提供的全局异常处理器,更清晰的输出错误内容和调用栈信息,代码如下

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

这时候就能看到输出内容如下:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

一下子就清楚很多。当然,该配置项也可以用来集成错误追踪服务 Sentry 和 Bugsnag。推荐阅读:Vue3 如何实现全局异常处理?

7. 观察 ref 的数据不直观,不方便

当我们在控制台输出ref声明的变量时。

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

会看到控制台输出了一个RefImpl对象:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)


看起来很不直观。我们都知道,要获取和修改ref声明的变量的值,需要通过.value来获取,所以你也可以:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

这里还有另一种方式,就是在控制台的设置面板中开启 「Enable custom formatters」选项。

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

image.png

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

image.png

这时候你会发现,控制台输出的ref的格式发生变化了:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

更加清晰直观了。

I discovered this method in "Vue.js Design and Implementation", but I couldn't find any relevant introduction in the documentation. If anyone finds it, please let us know~

2. Vite

1. Problems with using Vite dynamic import

Document address:cn.vitejs.dev/ guide/featu…

Students who use webpack should know that in webpack you can dynamically import files throughrequire.context:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

In Vite, we can use these two methods to dynamically import files:

  • import.meta.glob

The files matched by this method arelazy loadingby default, which is implemented throughdynamic import. When building, it willseparate independent chunks, which isasynchronous import, returns a Promise, which requires asynchronous operation. The usage method is as follows:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

  • ##import.meta.globEager
This method is

directly importing all modules, and issynchronously importing, and the returned result can be operated directly through thefor...inloop , the usage is as follows:

115 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

If you only use asynchronous import of Vue3 components, you can also directly use the Vue3 defineAsyncComponent API to load:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

2. Vite configuration alias type alias

Document address:

cn.vitejs.dev/config/#res…

When the project is more complex, it is often necessary to configure the alias path alias to simplify some code:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

The configuration in Vite is also very simple, just

vite.config.tsJust configure it inresolve.alias:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

If you are using TypeScript, the editor will prompt Warning that the path does not exist⚠️. At this time, you can add the configuration of

compilerOptions.pathsintsconfig.json:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

3. Vite configure global scss

Document address:

cn.vitejs.dev/config/#css…

When When we need to use scss configured theme variables (such as

$primary), mixin methods (such as@mixin lines), etc., such as:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

We can configure the scss theme configuration file in

vite.config.tscss.preprocessorOptions.scss.additionalData:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

If you don’t want to use the scss configuration file, you can also write the scss code directly:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

3. VueRouter

1. Obtain routing parameters in script-setup mode

Document address:

router.vuejs.org/zh/guide/ad…

Since in

script-setupmode, nothiscan be used, you cannot directly passthis.$routerorthis. $routeto obtain routing parameters and jump routes. When we need to obtain routing parameters, we can use theuseRoutemethod provided byvue-routerto obtain them, as follows:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

If you want to do a route jump, you can use the return value of theuseRoutermethod to jump:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

4. Pinia

1. Store destructured variables are not updated after modification

Document address:pinia.vuejs.org/core-concep…

When we deconstruct the store variable and then modify the value of the variable on the store, the view is not updated:

215 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

At this time After clicking the button to trigger thechangeNameevent, thenameon the view has not changed. This is because the store is a reactive object, and when destructured, its responsiveness will be destroyed. So we cannot deconstruct directly. In this case, you can use thestoreToRefstool method provided by Pinia. It is also very simple to use. You only need to wrap the object that needs to be deconstructed through thestoreToRefsmethod, and the other logic remains unchanged:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

If you modify the value in this way, the view will be updated immediately.

2. How Pinia modifies the data status

According to the plan given by the official website, there are currently three ways to modify it:

  • Modify the status of a single data throughstore.Attribute nameassignment;

This method is used in the previous section:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

  • Modify the status of multiple data through the$patchmethod;

Document address:pinia .vuejs.org/api/interfa…

When we need to modify the status of multiple data at the same time, if we still follow the above method, we may write like this:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

There is nothing wrong with writing the above, but Pinia’s official website has stated that using$patchwill be more efficient and perform better, so when modifying multiple pieces of data, it is more It is recommended to use$patch, and the usage method is also very simple:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

  • Modify multiple strokes through theactionmethod The status of the data;

You can also define a method of actions in the store to update:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

When used:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

These three methods can update the data status of the store in Pinia.

5. Element Plus

1. @charset warning when element-plus is packaged

Newly installed element- Plus is normal during the development stage and does not prompt any warnings. However, during the packaging process, the console outputs the following warning content:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

I have read it in the official issues for a long time:github.com/element-plu…

Try to configurecharset: falseinvite.config.ts, the result is also invalid:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

Finally found the solution in the official issues:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

2. Chinese language pack configuration

Document address:element-plus.gitee.io/zh-CN/guide…

The default components of elemnt-plus are in English:

315 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

We can switch to Chinese by introducing the Chinese language pack and adding it to the ElementPlus configuration:

15 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

At this time, you can see that the text of the components in ElementPlus becomes Chinese.

415 common problems in Vue3 family bucket development (helping you avoid pitfalls quickly)

Summary

The above is my summary of pitfall avoidance experience after three recent projects from getting started to actual Vue3 family bucket. Many of them are introduced in the documentation, but I’m just not familiar with them at first. I also hope that everyone will read the documentation more~

Vue3 script-setup mode does become more and more popular the more you write it.

If there are any questions about the content of this article, everyone is welcome to comment and discuss it.

[Related video tutorial recommendations:vuejs entry tutorial,web front-end entry]

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete