全局注册Vue.directive

1.src目录下新建directives文件

export default {
    install: function(Vue, option) {
        // 1:el指绑定的dom元素
        // 2:binding一个对象,包含指令的很多信息, 使用时可以绑定的值
        // 3:VUE编译生成的虚拟节点
        Vue.directive('change-color', (el,binding,vnode) => {
            el.style['color'] = binding.value
        })
    }
}

2.min.js中全局引入

import directive from './directive/directive' // 引入directive

Vue.use(directive) // 引入directive

3.组件中使用自定义指令

<template>
  <el-row :gutter="6" class="box">
      <!-- directive第一个参数就是绑定的指令名称 -->
      <div v-change-color="color">点我</div>
  </el-row>
</template>

<script>
export default {
  name: 'BigScreen',
  data() {
    return {
        color: 'red'
    }
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/wjsy/p/12174941.html
今日推荐