Home > Article > Web Front-end > 7 points that are easily overlooked when using Vue technology
This time I will bring you 7 points that are easily overlooked when using vue technology. What are the precautions when using vue technology. Here are practical cases, let’s take a look.
Preface
This article is a sharing of vue source code contribution value by Chris Fritz in a public place. I feel that there are many things worth learning from. , although I also do this at work for some content, I still translate the master’s ppt here, hoping to bring some help to my friends.
1. Make good use of the immediate attribute of watch
This is what I also wrote in the project. For example, if there is a request that needs to be executed once before it is initialized, and then monitor its changes, many people write like this:
created(){ this.fetchPostList() }, watch: { searchInputValue(){ this.fetchPostList() } }
We can write the above as follows:
watch: { searchInputValue:{ handler: 'fetchPostList', immediate: true } }
2. Component registration is worth learning from
Generally, our components are written as follows:
import BaseButton from './baseButton' import BaseIcon from './baseIcon' import BaseInput from './baseInput' export default { components: { BaseButton, BaseIcon, BaseInput } } <BaseInput v-model="searchText" @keydown.enter="search" /> <BaseButton @click="search"> <BaseIcon name="search"/></BaseButton>
There are generally three steps,
The first step is introduction,
the second step is registration,
the third step is formal use,
This is also the most common and common way of writing. However, this writing method is classic. There are many components that need to be introduced and registered multiple times, which is very annoying.
We can use webpack to create our own (module) context using the <a href="http://www.php.cn/wiki/136.html" target="_blank">require</a>.context()
method to achieve automatic dynamic require components.
The idea is: in main.js under the src folder, use webpack to dynamically package all the required basic components.
The code is as follows:
import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' // Require in a base component context const requireComponent = require.context( ‘./components', false, /base-[\w-]+\.vue$/ ) requireComponent.keys().forEach(fileName => { // Get component config const componentConfig = requireComponent(fileName) // Get PascalCase name of component const componentName = upperFirst( camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')) ) // Register component globally Vue.component(componentName, componentConfig.default || componentConfig) })
In this way, we only need the third step to introduce components:
<BaseInput v-model="searchText" @keydown.enter="search" /> <BaseButton @click="search"> <BaseIcon name="search"/> </BaseButton>
3. Simplify the introduction of modules in vuex
For vuex, we output the store as follows:
import auth from './modules/auth' import posts from './modules/posts' import comments from './modules/comments' // ... export default new Vuex.Store({ modules: { auth, posts, comments, // ... } })
We need to introduce a lot of modules, and then register them in Vuex.Store~~
Simplified The method is similar to the above. It also uses require.context() to read the file. The code is as follows:
import camelCase from 'lodash/camelCase' const requireModule = require.context('.', false, /\.js$/) const modules = {} requireModule.keys().forEach(fileName => { // Don't register this file as a Vuex module if (fileName === './index.js') return const moduleName = camelCase( fileName.replace(/(\.\/|\.js)/g, '') ) modules[moduleName] = { namespaced: true, ...requireModule(fileName), } }) export default modules
In this way, we only need the following code:
import modules from './modules' export default new Vuex.Store({ modules })
4. Delayed loading of routing
Regarding this point, regarding the introduction of vue, I have also mentioned it before in the key points and summary of vue project reconstruction techniques. You can pass Dynamically load components using require or import() methods.
{ path: '/admin', name: 'admin-dashboard', component:require('@views/admin').default }
or
{ path: '/admin', name: 'admin-dashboard', component:() => import('@views/admin') }
Load the route.
5. Router key component refresh
The following scene really breaks the hearts of many programmers... First of all, let’s acquiesce. Vue-router is used to implement routing control. Suppose we are writing a blog website and the requirement is to jump from /post-haorooms/a to /post-haorooms/b. Then we surprisingly discovered that the data was not updated after the page jumped? ! The reason is that vue-router "intelligently" discovered that this is the same component, and then it decided to reuse this component, so the method you wrote in createdfunction was not executed at all. The usual solution is to monitor changes in $route to initialize the data, as follows:
data() { return { loading: false, error: null, post: null } }, watch: { '$route': { handler: 'resetData', immediate: true } }, methods: { resetData() { this.loading = false this.error = null this.post = null this.getPost(this.$route.params.id) }, getPost(id){ } }
The bug is solved, but is it too inelegant to write like this every time? Adhering to the principle of being lazy if you can, we hope that the code will be written like this:
data() { return { loading: false, error: null, post: null } }, created () { this.getPost(this.$route.params.id) }, methods () { getPost(postId) { // ... } }
Solution: Add a unique key to router-view, so that even if it is a public component, as long as the URL changes, it will be re- Create this component.
<router-view :key="$route.fullpath"></router-view>
Note: From my personal experience, this is generally used in sub-routes, so as not to avoid a large number of redraws. Assuming that this attribute is added to the root directory of app.vue, then every time you click to change the address, it will be redrawn. , it’s still not worth the gain!
6. The only component root element
The scenario is as follows:
(Emitted value instead of an instance of Error)
Error compiling template:
- Component template should contain exactly one root element.
If you are using v-if on multiple elements, use v-else-if
to chain them instead.
模板中p只能有一个,不能如上面那么平行2个p。
例如如下代码:
<template> <li v-for="route in routes" :key="route.name" > <router-link :to="route"> {{ route.title }} </router-link> </li> </template>
会报错!
我们可以用render函数来渲染
functional: true, render(h, { props }) { return props.routes.map(route => <li key={route.name}> <router-link to={route}> {route.title} </router-link> </li> ) }
七、组件包装、事件属性穿透问题
当我们写组件的时候,通常我们都需要从父组件传递一系列的props到子组件,同时父组件监听子组件emit过来的一系列事件。举例子:
//父组件 <BaseInput :value="value" label="密码" placeholder="请填写密码" @input="handleInput" @focus="handleFocus> </BaseInput> //子组件 <template> <label> {{ label }} <input :value="value" :placeholder="placeholder" @focus=$emit('focus', $event)" @input="$emit('input', $event.target.value)" > </label> </template>
这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写:
<input :value="value" v-bind="$attrs" v-on="listeners" > computed: { listeners() { return { ...this.$listeners, input: event => this.$emit('input', event.target.value) } } }
$attrs包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs"
传入内部组件。
$listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners"
传入内部组件。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of 7 points that are easily overlooked when using Vue technology. For more information, please follow other related articles on the PHP Chinese website!