Vue CLI 系列之(六)插件
插件
-
功能:用于增强Vue
-
本质:包含install方法的一个对象,install的第一个参数是Vue构造函数,第二个以后的参数是插件使用者传递的数据。
-
定义插件:
对象.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 } -
暴露插件
-
使用插件:
Vue.use() -
注:
(1)main.js中不要直接定义插件
(2)文件名建议命名为plugins
(3)插件中的install方法是Vue帮我们调用的,只有应用了插件Vue才会帮我们调用install方法
(4)main.js中创建vm之前要应用插件
express、koa通过use应用中间件
-
使用
定义插件
// 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) })

浙公网安备 33010602011771号