Vue 插件介绍

功能:用于增强Vue

本质:包含install方法的一个对象,install的第一个参数是Vue,第2个以后的参数是插件使用者传递的数据。

1、定义插件:

对象.install = function(Vue,options){

//(1)添加全局过滤器

Vue.filter(...)

//(2)添加全局指令

Vue.directive(...)

//(3)配置全局混入(混合)

Vue.mixin(...)

//(4)添加实例方法

Vue.prototype.$myMethod = function(){...}

Vue.prototype.$myProperty = xxx

}

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

案例:

(1)定义插件

const obj = {
    install(Vue){
        console.log('@@@ install:'+Vue)

        //全局过滤器
        Vue.filter("mySlice2",function(value){
            return value.slice(0,5)
        })

        //全局自定义指令
        Vue.directive("fbind-number",{
            //指令与元素成功绑定时调用
            bind(element,binding){
                element.value = binding.value*10;
            },
            //指令所在元素被插入页面时调用
            inserted(element,binding){
                element.focus()
            },
            //指令所在的模板被重新解析时调用
            update(element,binding){
                element.value = binding.value*10;
            }
        })

        //全局混入
        Vue.mixin({
            data(){
                return{
                    x:100,
                    y:200
                }
            }
        })

        //全局方法(给Vue原型添加一个方法)
        Vue.prototype.hello = ()=>{
            alert("你好啊~")
        }
    
    }
}

export default obj

(2)在main.js 引入插件

//引入插件,应用插件
import plugins from "./plugins/plugins"
Vue.use(plugins)

(3)在组件中应用插件中的东西(过滤器、指令、方法、混入)

<template>
  <div class="school">
      <h3>学校名:{{SchoolName | mySlice2}}</h3> <!-- 插件中的过滤器 -->
      <h3>学校地址:{{address}}</h3>
      <input type="text" v-fbind-number="n"><br/> <!-- 插件中的指令 -->
      <button @click="hello">点我测试hello方法</button> <!-- 插件中的方法 -->
  </div>
</template>

<script>

export default {
    name:"School",
    data(){
        return{
            SchoolName:"尚硅谷123456789",
            address:"北京昌平",
            n:2
        }
    },
   
}
</script>

(4)效果

 

posted @ 2023-02-26 14:44  codeing123  阅读(57)  评论(0编辑  收藏  举报