Vue plugin插件的使用

一、前言

插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码。

本文主要介绍了vue中 plugin插件的用法及其功能。

二、用法

定义plugin需要使用 install 方法。这个方法有两个参数app、options(可选)

const myPlugin = {
   install(app, options){
       console.log(app, options); 
    }
}
app.use(myPlugin,{name: '张三'})

打开控制台看看app, options分别会输出什么内容:
在这里插入图片描述
从图中可以看出,app包含有directive自定义指令、mixin混入以及config配置等内容,options里面是使用插件传入的{ name: ‘张三’ }

三、例子

1、添加directive

plugin.js:

// plugin.js
export const myPlugin = {
    install(Vue) {
        Vue.directive('focus', {
            inserted(el,bindings){
                el.value = bindings.value
                el.focus()
            }
        })
    }
}

main.js:

import Vue from 'vue'
import App from './App.vue'
import { myPlugin } from './plugins'

Vue.config.productionTip = false

// 使用插件
Vue.use(myPlugin)

new Vue({
  render: h => h(App),
}).$mount('#app')

demo.vue:

<template>
  <div>
    <span >{{ msg }}</span>
    <input type="text" v-focus="msg">
  </div>
</template>

<script>
export default {
  data: () => ({}),
  props: ["msg"],
};
</script>

2、添加mixin

export const myPlugin = {
    install(Vue) {
        Vue.directive('focus', {
            inserted(el,bindings){
                el.value = bindings.value
                el.focus()
            }
        })
        Vue.mixin({
           mounted(){
                console.log('mixin');
            }
        })
    }
}

控制台成功输出:mixin
在这里插入图片描述

3、添加config

export const myPlugin = {
    install(Vue) {
        Vue.directive('focus', {
            inserted(el,bindings){
                el.value = bindings.value
                el.focus()
            }
        })
        Vue.mixin({
           mounted(){
                console.log('mixin');
            }
        })
        // 定义一个实例方法,定义在Vue的原型上 Vue.prototype.xxx
        Vue.prototype.message = function(val){
          console.log(val);
        }
        //定义一个过滤器
        Vue.filter('fmtDate', function(val){
          return moment(val).format('YYYY-MM-DD')
        });
        Vue.config.globalProperties.$sayHello = 'hello';
    }
}

在组件中:

console.log(this.$sayHello )

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老电影故事

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值