Home > headlines > 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)

青灯夜游
Release: 2022-10-21 20:24:28
forward
3840 people have browsed it

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 the script-srtup mode, I directly use the life cycle function of Vue3.x:

// A.vue\
<script setup>\
import { ref, onMounted } from "vue";\
let count = ref<number>(0);\
\
onMounted(() => {\
count.value = 1;\
})\
</script>
Copy after login

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 use global compilation The defineExpose macro 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:

// 子组件\
<script setup>\
let name = ref("pingan8787")\
defineExpose({ name }); // 显式暴露的数据,父组件才可以获取\
</script>\
\
// 父组件\
<Chlid ref="child"></Chlid>\
<script setup>\
let child = ref(null)\
child.value.name //获取子组件中 name 的值为 pingan8787\
</script>
Copy after login

Note:

  • Global compiler macros can only be used in script- Used in setup mode; in
  • script-setup mode, macros can be used directly without import;
  • 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 four global compilations provided by script-setup mode were introduced earlier Device macro has not been introduced in detail yet. This section introduces defineProps and withDefaults. The defineProps macro can be used to define the input parameters of the component, as follows:

<script setup>\
let props = defineProps<{\
schema: AttrsValueObject;\
modelValue: any;\
}>();\
</script>
Copy after login

Only define the schema and # in the props attribute here. ##modelValueTwo attribute types, defineProps The 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:

<script setup>\
let props = withDefaults(\
defineProps<{\
schema: AttrsValueObject;\
modelValue: any;\
}>(),\
{\
schema: [],\
modelValue: &#39;&#39;\
}\
);\
</script>
Copy after login

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;
Copy after login

使用时需要先通过 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-bind 和 v-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)

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

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 through require.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 are lazy loading by default, which is implemented through dynamic import. When building, it will separate independent chunks, which is asynchronous 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 is synchronously importing, and the returned result can be operated directly through the for...in loop , 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.ts Just configure it in resolve.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.paths in tsconfig.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.ts css.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-setup mode, no this can be used, you cannot directly pass this.$router or this. $route to obtain routing parameters and jump routes. When we need to obtain routing parameters, we can use the useRoute method provided by vue-router to 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 the useRouter method 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 the changeName event, the name 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 the storeToRefs 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 the storeToRefs method, 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 through store.Attribute name assignment;

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 $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:

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 $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:

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

  • Modify multiple strokes through the action method 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 configure charset: false in vite.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]

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template