vue 自定义指令

1、全局注册自定义指令

1、创建一个公共的js文件

import Vue from 'vue'
Vue.directive('demo', {
    bind: function (el, binding) {
        console.log(el);
        console.log(binding.arg);
        el.innerHTML = binding.value
    }
})

2、main.js中引入 

import App from './App'
import "./js/index" //创建的js文件

Vue.config.productionTip = false

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

3、组件使用

<template>
  <div class="hello">
    <div v-demo:f="200"></div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      f: "left",
    };
  },

  components: {},

  methods: {},
};
</script>

<style scoped>
</style>

2、局部自定义组件

<template>
  <div class="hello">
    <div v-test:left="name"></div>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      obj: {
        a: 0,
      },
      name: "我是名字",
    };
  },
  directives: {
    test: {
      bind: function (el, binding, vnode, oldVnode) {
        var s = JSON.stringify;
        el.innerHTML =
          "name: " +
          s(binding.name) +
          "<br>" +
          "value: " +
          s(binding.value) +
          "<br>" +
          "expression: " +
          s(binding.expression) +
          "<br>" +
          "argument: " +
          s(binding.arg) +
          "<br>" +
          "modifiers: " +
          s(binding.modifiers) +
          "<br>" +
          "vnode keys: " +
          Object.keys(vnode).join(", ");
      },
    },
  },
  components: {},

  methods: {},
};
</script>

<style scoped>
</style>
上一篇:android开发EditText禁止输入中文密码的解决方法


下一篇:Vue常用特性