vue常用操作技巧

1、组件注册,随时随地在页面中使用这些高频组件,无需手动一个个引入

// global.js文件
import Vue from 'vue'
//转换单词首字母大写
function changeStr(str){
  return str.charAt(0).toUpperCase() + str.slice(1)
}
//把组件放在src目录下components下,获取所有.vue文件
const requireComponent = require.context('@components', true, /.vue$/)
//查找
const install = () => {
  //例如:fileName = ./child.vue
  requireComponent.keys().forEach(fileName => {
    //拿到名字对应的组件
    let config = requireComponent(fileName)
    //去除./,只留下文件名
    let componentName = changeStr(fileName.replace(/^.//, ''))
    //注册组件
    Vue.component(componentName, config.default || config)
  })
}
export default {
  install
}

在main.js中,导入global.js

import scan from './global.js'

Vue.use(scan)

2、高精度权限控制——自定义指令directive

通常使用v-if或者v-show来做权限判断。如果判断条件繁琐且多个地方需要判断,很不方便。可以通过全局自定义指令来处理。

//新建权限存储函数
export function checkArray(key){
  let arr = ['1', '2', '3', '4', 'demo']
  let index = arr.indexOf(key)
  if(index > -1){
    return true
  }else{
    return false
  }
}

将array文件挂在到全局

import { checkArray } from './array.js'
Vue.directive("permission", {
  inserted(el, binding) {
    let permission = binding.value
    if(permission){
      let hasPermission = checkArray(permission)
      if(!hasPermission){
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
})

 使用

    <div>
        <button v-permission="'1'">A</button>
        <button v-permission="'10'">B</button>
        <button v-permission="'3'">C</button>
    </div>

 3、v-for和click同时存在,循环绑定事件,将事件写在父元素上

   <div @click="parentClick($event)">
      <div v-for="item in 10" :a="item" :key="item">
            {{item}}
      </div>
    </div>

    parentClick(event){
      console.log(event.target.getAttribute("a"))
    }
原文地址:https://www.cnblogs.com/zmyxixihaha/p/13143285.html