Vue 自定义插件

2022-03-18  本文已影响0人  洪锦一

pligins.js

export default {
    install(Vue, ...arg) {
        console.info("接收的参数:", ...arg);
        // 全局过滤器
        Vue.filter('mySlice', function (value) {
            return value.slice(0, 4)
        })

        //函数全局自定义指令
        Vue.directive('big', function (el, binding) {
            el.innerText = binding.value * 10;
        })

        // 对象全局自定义指令
        Vue.directive('fbind', {
            bind(el, binding) {
                console.log("bind");
                el.value = binding.value;
            },
            // 指令所在元素被插入页面时调用
            inserted(el, binding) {
                console.log("inserted", binding);
                el.focus();
            },
            // 指令所在的模板被重新解析时
            update(el, binding) {
                console.log("update");
                el.value = binding.value;
                el.focus();
            },
        })

        // 定义混入
        Vue.mixin({
            data() {
                return {
                    x: 100,
                    y: 200
                };
            },
        })

        // vue原型上添加一个方法
        Vue.prototype.hello = () => {
            alert("hello")
        }

    }
}

在main.js引入

// 引入插件
import pligins from "./pligins/pligins.js"

// 应用插件
Vue.use(pligins, '参数1', '参数2', '参数3', '...')

在vue组件中应用

<template>
  <div>
    <p>未使用过滤器:{{ name }}</p>
    <p>已使用过滤器:{{ name | mySlice }}</p>

    <p v-big="age"></p>

    <input type="text" v-fbind="age" />

    <p>{{ x }}-{{ y }}</p>

    <button @click="showHello">测试全局插件</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "张三是一个调皮的孩子",
      age: 20,
    };
  },
  methods: {
    showHello() {
      this.hello();
    },
  },
};
</script>

<style>
</style>
上一篇 下一篇

猜你喜欢

热点阅读