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!
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:
(Learning video sharing:vue video tutorial)
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:
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-srtup
mode, 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…
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 macro
exposes 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:
import
;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 introducesdefineProps
andwithDefaults
. ThedefineProps
macro can be used to define the input parameters of the component, as follows:
Only define theschema
and # in theprops
attribute here. ##modelValueTwo attribute types,
definePropsThe shortcoming of this declaration is that it does not provide a way to set the default value of props.
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.
Document address:
在 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
方法获取实例对象:
当我们在使用v-model
指令的时候,实际上v-bind
和v-on
组合的简写,Vue2.x 和 Vue3.x 又存在差异。
Vue2.x
在子组件中,如果要对某一个属性进行双向数据绑定,只要通过this.$emit('update:myPropName', newValue)
就能更新其v-model
绑定的值。
script-setup
模式下就不能使用this.$emit
去派发更新事件,毕竟没有this
,这时候需要使用前面有介绍到的 defineProps、defineEmits 两个宏来实现:
父组件使用的时候就很简单:
Vue3.x 对于一些开发过程中的异常,做了更友好的提示警告,比如下面这个提示:
这样能够更清楚的告知异常的出处,可以看出大概是
这时候就能看到输出内容如下:
一下子就清楚很多。当然,该配置项也可以用来集成错误追踪服务 Sentry 和 Bugsnag。推荐阅读:Vue3 如何实现全局异常处理?
当我们在控制台输出ref
声明的变量时。
会看到控制台输出了一个RefImpl
对象:
看起来很不直观。我们都知道,要获取和修改ref
声明的变量的值,需要通过.value
来获取,所以你也可以:
这里还有另一种方式,就是在控制台的设置面板中开启 「Enable custom formatters」选项。
image.png
image.png
这时候你会发现,控制台输出的ref
的格式发生变化了:
更加清晰直观了。
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~
Document address:cn.vitejs.dev/ guide/featu…
Students who use webpack should know that in webpack you can dynamically import files throughrequire.context
:
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:
directly importing all modules, and issynchronously importing, and the returned result can be operated directly through thefor...inloop , the usage is as follows:
Document address:When the project is more complex, it is often necessary to configure the alias path alias to simplify some code: The configuration in Vite is also very simple, just
vite.config.tsJust configure it in
resolve.alias:
compilerOptions.pathsin
tsconfig.json:
Document address:When When we need to use scss configured theme variables (such as
$primary), mixin methods (such as
@mixin lines), etc., such as:
vite.config.tscss.preprocessorOptions.scss.additionalData
:
Document address:Since in
script-setupmode, no
thiscan be used, you cannot directly pass
this.$routeror
this. $routeto obtain routing parameters and jump routes. When we need to obtain routing parameters, we can use the
useRoutemethod provided by
vue-routerto obtain them, as follows:
If you want to do a route jump, you can use the return value of theuseRouter
method to jump:
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:
At this time After clicking the button to trigger thechangeName
event, thename
on 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 thestoreToRefs
tool method provided by Pinia. It is also very simple to use. You only need to wrap the object that needs to be deconstructed through thestoreToRefs
method, and the other logic remains unchanged:
If you modify the value in this way, the view will be updated immediately.
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 name
assignment;
This method is used in the previous section:
Modify the status of multiple data through the$patch
method;
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:
There is nothing wrong with writing the above, but Pinia’s official website has stated that using$patch
will 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:
Modify multiple strokes through theaction
method The status of the data;
You can also define a method of actions in the store to update:
When used:
These three methods can update the data status of the store in Pinia.
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:
I have read it in the official issues for a long time:github.com/element-plu…
Try to configurecharset: false
invite.config.ts
, the result is also invalid:
Finally found the solution in the official issues:
Document address:element-plus.gitee.io/zh-CN/guide…
The default components of elemnt-plus are in English:
We can switch to Chinese by introducing the Chinese language pack and adding it to the ElementPlus configuration:
At this time, you can see that the text of the components in ElementPlus becomes Chinese.
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]