在main.js中使用Vue.directive({'directiveName',bind(el,binding,vnode)});
注:Vue.directive要写在new Vue之前
参数说明:el 是使用自定义指令的标签
binding.value是指令中等号后的值
binding.arg是指令中冒号后值
例子:
main.js
import Vue from 'vue' import App from './App' Vue.config.productionTip = false Vue.directive("test",{ bind(el,binding,vnode){ el.style.background = "red" } }) //bind.value 是指指令等号后的内容 Vue.directive('green',{ bind(el,binding,vnode){ if(binding.value=="200"){ el.style.background = "green" el.style.width = "200px" el.style.height = "200px" } } }) //bind.value 是指指令冒号后面的内容 Vue.directive('orange',{ bind(el,binding,vnode){ if(binding.arg =="set"){ el.style.background = "orange" el.style.width = "200px" el.style.height = "200px" } } }) /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>' })
Home.vue
<template> <div> <div class="one" v-test></div> <div v-green="200"></div> <div v-orange:set></div> </div> </template> <script> export default { name: "Home", data () { return { }; } } </script> <style lang="css" scoped> .one{ width: 200px; height: 200px; } </style>