美文网首页vue学习
Vue基础-插件

Vue基础-插件

作者: 大炮打小鸟 | 来源:发表于2025-09-18 22:08 被阅读0次

功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
定义插件:

对象.install = function(Vue,options){
   //1.添加全局过滤器
   Vue.filter(....)
   //2.添加全局指令
   Vue.directive(....)
   //3.配置全局混入(合)
   Vue.mixin(....)
   //4.添加实例方法
   Vue.prototype.$myMethod = function(){...}
   Vue.prototype.$myProperty = xxxx
}

使用插件:Vue.use()

例子:
创建plugins.js文件

export default {
    install(Vue) {
        //可以定义全局过滤器
        Vue.filter("mySclice", function (value) {
            return value.slice(0, 4)
        })

        //定义全局指令
        Vue.directive('fbind', {
            //指令与元素绑定时
            bind(element, binding) {
                element.value = binding.value
            },
            //指令所在元素被插入页面时
            inserted(element, binding) {
                element.focus()
            },
            //指令所在模版被重新解析时
            update(element, binding) {
                element.value = binding.value
            }
        })
        //定义混入
        Vue.mixin({
            data() {
                return {
                    x: 100,
                    y: 200
                }
            },
        })
        //给Vue原型上添加一个方法
        Vue.prototype.hello = () => {

        }
    }
}

使用,main.js中:

//插件
import plugins from './plugins'
Vue.use(plugins)

相关文章

网友评论

    本文标题:Vue基础-插件

    本文链接:https://www.haomeiwen.com/subject/fnnuzjtx.html