前端日常工作中常用开发小技巧 ---Vue

1.路由懒加载

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      component: () => import("xxx")
    }
]
})

2.动态组件

做一个 tab 切换时就会涉及到组件动态加载

<component v-bind:is="currentTabComponent"></component>

但是这样每次组件都会重新加载,会消耗大量性能,所以 <keep-alive> 就起到了作用

<keep-alive>
  <component v-bind:is="currentTabComponent"></component>
</keep-alive>

3.mixins ---- 有些组件有些重复的 js 逻辑 ,mixins 就可以实现这种混入

const mixin={
    created(){
      this.dealTime()
    },
    methods:{
      dealTime(){
        console.log('这是mixin的dealTime里面的方法');
      }
  }
}

export default{
  mixins:[mixin]
}

4.为路径设置别名

// vue-cli 2.x 配置
// 在 webpack.base.config.js中的 resolve 配置项,在其 alias 中增加别名
resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },

// vue-cli 3.x 配置
// 在根目录下创建vue.config.js
var path = require('path')
function resolve (dir) {
  console.log(__dirname)
  return path.join(__dirname, dir)
}
module.exports = {
  chainWebpack: config => {
    config.resolve.alias
      .set(key, value) // key,value自行定义,比如.set('@@', resolve('src/components'))
  }
}

5.页面统一判断

//在开发中经常会遇到权限判断的问题,我们又不可能在每一个页面的生命周期中去判断一下,那样太消耗时间了,处理方式:
router.beforeEach((to, from, next) => {
  myAccess.checkhaveAccess(to.path) === true ? next() : next('/forbid')
})

6.路由的项目启动页和 404 页面

//404 页面指的是: 当进入一个没有 声明/没有匹配 的路由页面时就会跳转到 404 页面
export default new Router({
  routes: [
    {
      path: '/', // 项目启动页
      redirect:'/login'  // 重定向到下方声明的路由
    },
    {
      path: '*', // 404 页面
      component: () => import('./notfind')
    },
  ]
})
原文地址:https://www.cnblogs.com/aixue/p/13214328.html