在 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>
来源: http://www.bubuko.com/infodetail-3051992.html