vue的插件其实通过Vue这个对象,为Vue或者它的原型链上添加新的属性。或者调用Vue的api完成其他事情,例如添加自定义指令或者过滤器。
(1)新建vue-Plugin.js文件,写入
(2)为Vue这个对象添加一系列属性方法,或者注册全局的过滤器和自定义指令
(3)引入使用script引入vue-Plugin.js文件,要确保此前vue已经被引入
//vue-Plugin.js
//确保在这之前已经引入了vue这个框架
//为所有的Vue实例挂载一个$getMsg属性
Vue.prototype.$getMsg = function(cb){
//利用延时定时器返回一个数据
setTimeout(function(){
var res = "返回的数据"
//模拟异步执行回调函数
cb && cb(res)
},2000)
}
//添加全局的自定义指令
Vue.directive('upper-text',function(el,binding){
el.innerText = binding.value.toUpperCase();
})
//添加全局过滤器
Vue.filter('toLowerCase',function(val){
return val.toLowerCase()
})
//添加类方法
Vue.myGlobalMethod = function(){
console.log('我是Vue的类方法')
}
引入插件
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="vue-Plugin.js"></script>
使用插件
<body>
<div id="app">
<p v-html="msg"></p>
<!-- 使用插件的自定义指令 -->
<p v-upper-text="msg"></p>
<!-- 使用过滤器 -->
<p>{{msg | toLowerCase}}</p>
<p>{{content}}</p>
</div>
</body>
<script>
var vm = new Vue({
el:'#app',
data:{
msg:'Good Life',
content:'默认的值'
},
mounted(){
//页面初次渲染后请求数据
this.$getMsg((res) => {
this.content = res
})
},
updated(){
//页面更新后调用Vue的类方法
Vue.myGlobalMethod()
}
})
</script>
脚手架项目中各个模块是相互独立的,其他模块无法直接读取Vue这个对象。只能通过函数传参的形式将Vue传入到另外一个模块中,这个模块接收以后再对Vue对象进行操作。
Vue中有一个方法可以将Vue这个对象传递给vue的插件模块,他就是Vue.use()
Vue.use(plugin)这个方法执行后,会运行plugin.install(Vue)。并将Vue作为参数传递给这个模块,之后这个模块就可以对Vue这个对象进行操作了
所以前面的插件可以改写成:
(1)在src/plugin目录下新建myPlugin.js,写入
(2)创建一个对象myPlugin,并暴漏出去
(3)为myPlugin对象添加install方法,接收Vue这个对象
(4)在install方法中对Vue这个对象进行操作
(5)入口js文件中引入相关模块,并运行Vue.use(myPlugin)
//myPlugin.js
//创建对象
var myPlugin = {}
//为对象添加install方法,接收Vue这个对象
myPlugin.install = function(Vue){
//测试
console.log('install方法执行了')
//为所有的Vue实例挂载一个$getMsg属性
Vue.prototype.$getMsg = function(cb){
//利用延时定时器返回一个数据
setTimeout(function(){
var res = "返回的数据"
//模拟异步执行回调函数
cb && cb(res)
},2000)
}
//添加全局的自定义指令
Vue.directive('upper-text',function(el,binding){
el.innerText = binding.value.toUpperCase();
})
//添加全局过滤器
Vue.filter('toLowerCase',function(val){
return val.toLowerCase()
})
//添加类方法
Vue.myGlobalMethod = function(){
console.log('我是Vue的类方法')
}
}
//暴漏该对象
export default myPlugin
//入口文件
import Vue from 'vue'
import App from './App'
import myPlugin from './plugin/myPlugin.js'
Vue.use(myPlugin)
<template>
<div id="app">
<p>{{msg}}</p>
<!-- 使用插件的过滤器 -->
<p>{{msg | toLowerCase}}</p>
<!-- 使用插件的自定义指令 -->
<p v-upper-text="msg"></p>
<p>{{content}}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg:'Good Life',
content:'默认的值'
}
},
mounted(){
//页面初次渲染后请求数据
this.$getMsg((res) => {
this.content = res
})
}
}
</script>
下面的代码被执行了,说明Vue.use()这个语句执行后会调用plugin.install()
console.log('install方法执行了')
原文:https://www.cnblogs.com/OrochiZ-/p/11838999.html