1、功能:用于增强Vue

2、本质:包含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
    }

3、使用插件: Vue.use()

4、代码

4.1插件定义


export default {
    install(Vue){
        // console.log('@@@install hxm',Vue)
        //1.添加全局过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4)
        })
        //2.添加全局指令
        Vue.directive('fbind', {
            //指令与元素成功绑定时
            bind(el, binding) {
                el.value = binding.value
            },
            //指令所在元素成功插入界面时
            inserted(el, binding) {
                el.focus()
            },
            //指令所在的模板被重新解析时
            update(el, binding) {
                el.value = binding.value
            }
        });
        //3.配置全局混入(混合)
        Vue.mixin({
            data(){
                return{
                    x:100,
                    y:200
                }
            }
        })
        //4.添加实例方法:vm和vc就都能用了
        Vue.prototype.hello =()=>{alert('你好啊')}
    }
}


4.2 插件使用


<template>
  <div>
    <h1>{{ msg }}</h1>
    <!-- 管道符使用插件中 全局过滤器 -->
    <h2>学生姓名:{{name | mySlice}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <h2>学生年龄:{{age}}</h2>
    <!-- 使用插件中fbind全局指令 -->
    <input type="text" v-fbind:value="name">
    <br/>
    <br/>
    <!-- 使用全局中实例方法 -->
    <button @click="sayHi">点我测试hello方法</button>
  </div>
</template>
<script>
export default {
    name:'Student',
    data(){
        // console.log(this)   //输出的vc,包含data内的msg,以及props内的name,age,sex
        return{
            msg:'我是饥荒Boss',
            name:'猪人小鸭子',
            age:12,
            sex:'男'
        }
    },
    methods:{
        sayHi(){
            this.hello()
        }
    }
}
</script>


5、效果图