Vue CLI 系列之(六)插件

插件

  1. 功能:用于增强Vue

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

  3. 定义插件:

    对象.install = function (Vue, option1, option2, option3...) {
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例属性和实例方法,vm和vc都可以调用
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx
    }
    
  4. 暴露插件

  5. 使用插件:Vue.use()

  6. 注:

    (1)main.js中不要直接定义插件

    (2)文件名建议命名为plugins

    (3)插件中的install方法是Vue帮我们调用的,只有应用了插件Vue才会帮我们调用install方法

    (4)main.js中创建vm之前要应用插件

express、koa通过use应用中间件

  1. 使用

    定义插件

    // plugins.js
    export default {
    	install(Vue, a, b){
    		console.log(a, b)
    		Vue.filter('myFilter', function(val){
    			return val.slice(0, 4)
    		})
    		
    		Vue.directive('fbind', {
    			bind(element, binding){
    				console.log(binding)
    				element.value = binding.expression
    			},
    			inserted(element){
    				element.focus()
    			},
    			update(){
    				console.log('xxxx')
    			}
    		})
    		
    		Vue.mixin({
    			data(){
    				return {
    					kkk: 'hhh'
    				}
    			}
    		})
    		
    		Vue.prototype.a = 2
    		Vue.prototype.hello = function(){
    			console.log('点击了hello')
    		}
    	}
    }
    

    使用插件

    // main.js
    import Vue from 'vue'
    import App from './App.vue'
    import plugins from './plugins.js'
    Vue.config.productionTip = false
    
    Vue.use(plugins, 1, 22)
    new Vue({
    	el: '#app',
    	render: h => h(App)
    })
    
posted @   刘二水  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示