vue 技巧

便捷引入文件夹下的所有组件

require.context()

https://webpack.docschina.org/guides/dependency-management/#requirecontext

require.context是一个webpack的api,用来实现自动化导入模块,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块

语法

require.context(directory, useSubdirectories = true, regExp = /^./.*$/, mode = 'sync');

  • directory {String} -读取文件的路径
  • useSubdirectories {Boolean} -是否遍历文件的子目录
  • regExp {RegExp} -匹配文件的正则
/**
* @param directory 要搜索的文件夹目录不能是变量,否则在编译阶段无法定位目录
* @param useSubdirectories  是否搜索子目录
* @param regExp 匹配文件的正则表达式
* @return function 返回一个具有 resolve, keys, id 三个属性的方法
          resolve() 它返回请求被解析后得到的模块 id
          keys() 它返回一个数组,由所有符合上下文模块处理的请求组成。 
          id 是上下文模块里面所包含的模块 id. 它可能在你使用 module.hot.accept 的时候被用到
*/
require.context(directory, useSubdirectories = false, regExp = /^.//)

实例

const path = require('path')
const files = require.context('@/components', false, /\.vue$/)
const components = {}
files.keys().forEach(key => { 
      const name = path.basename(key, '.vue') 
      components[name] = files(key).default || files(key)
})
import Vue from 'vue';
import VueRouter from 'vue-router';
const files = require.context('./views', true, /router\.js$/);

Vue.use(VueRouter);

export const routes = [
    {
        path: '/',
        name: 'home',
        redirect: '/data-center'
    }
].concat(
    files.keys().reduce((res, item, index) => {
        res.push(...files(item).default);
        return res;
    }, [])
);

export default new VueRouter({
    mode: 'history',
    base: 'epidemic-prevention-platform',
    routes
});

更新props(.sync 修饰符)

.sync 修饰符

parent.vue

<child :title.sync="doc.title"></child>
// 等同于
<child v-on:update:title="doc.title"></child>

child.vue

export defalut {
    props: {
        title: String  
    },
    methods: {
        changeTitle(){
            this.$emit('update:title', 'hello')
        }
    }
}

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个 property (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

动态添加watch及卸载watch观察

($watch)[https://cn.vuejs.org/v2/api/#vm-watch]

语法:


数据观察还有另一种函数式定义的方式:

export default {
    data() {
        return {
            count: 1      
        }
    },
    created() {
        this.$watch('count', function(){
            console.log('count 新值:'+newVal)
        }, {
            immediate: true
        })
    }
}

这种方式使定义数据观察更灵活,而且 $watch 会返回一个取消观察函数,用来停止触发回调:

let unwatchFn = this.$watch('count', function(newVal){
    console.log('count 新值:'+newVal)
})
this.count = 2 // log: count 新值:2
unwatchFn()
this.count = 3 // 什么都没有发生...

只改变路由的params、query值时页面组件不刷新的问题

方法一:监测路由变化重新执行初始化

watch: {
      '$route.query.id': {
            this.init();
      }
}

方法二: 给router-view加key,保证路由切换时都会重新渲染

<template lang="pug">
.layout-wrappper
    .layout-page(ref="layout-page", key="layout-page")
        router-view(:key="viewKey")
</template>

import _ from 'lodash';
export default {
    computed: {
        viewKey () {
            return JSON.stringify(_.pick(this.$route, ['name', 'params', 'query']));
        }
    },
}
posted @ 2020-07-22 16:58  fanlinqiang  阅读(179)  评论(0)    收藏  举报