Vue源码分析(插件编写)
简介
插件的本质其实是一个普通函数,因此插件往往会结合mixin使用,即将重复的代码混入到Vue实例中,供组件复用。但是mixin是全局api,他会被应用到所有实例中。比较危险(doge)
因此较为优秀的方法是使用插件包裹,因为插件会自动删除且更加便于理解。所以我们推荐使用Vue.use
$options
每个组件中都有$.options
属性,它表示实例组件的配置项,当然这个配置项是多种多样的,例如组件自身的配置、继承的配置、全局mixin、自定义配置等。
定义插件方法
这里我们先抛出一个定义插件方法的结论,避免对之后的内容产生误解。
// install第一个参数为Vue,第二个参数为数据
插件对象.install = function (Vue, options) {
// 1. 添加全局过滤器
Vue.filter(....)
// 2. 添加全局指令
Vue.directive(....)
// 3. 配置全局混入(合)
Vue.mixin(....)
// 4. 添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxxx
}
[参考文章](Vue学习之--------Vue中自定义插件(2022/8/1)_銀-河的博客-CSDN博客_vue 定义插件)
编写一个简单的插件
看完上面的内容,是不是感觉更加云里雾里了。
让我们一起编写一个简单的插件来理解吧。
目标:创建一个处理自定义规则选项的插件,让Vue接收一个自定义属性rules
,该选项接收一些验证规则用于验证组件内data数据
// target
const vm = new Vue({
data: { foo: 10 },
rules: {
foo: {
validate: value => value > 1,
message: 'foo must be greater than one'
}
}
})
vm.foo = 0 // should log: "foo must be greater than one"
如果你仅仅是自定义一个rules
加入vue组件中,vue会忽略;但是当你调用钩子,就可以通过this.$options.rules
访问到,这也就是上面讲的每个组件都有$options
表示组件的配置项
created(){
this.$options.rules
}
当然Vue为了避免组件开发者自己手动调用钩子访问,因此使用Vue.mixin
内部抽象出来
例如
// 插件可以只是一个函数
const myPlugin = Vue =>{
Vue.mixin({
created(){
if(this.$options.rules){
// do something
}
}
})
}
// Vue自身也公开了install函数
const myPlugin = {
install(Vue){
Vue.mixin({
created(){
if(this.$options.rules){
// do something
}
}
})
}
}
Vue.use(myPlugin)
上面的代码是一个创建插件的模板代码,当我们调用Vue的时候插件还不会被使用,当Vue实例被创建后,通过Vue.use
,调用install()才会应用这个全局mixin,进而调用created钩子
// 引入Vue
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 编写插件
const RulesPlugin = {
install(Vue) {
Vue.mixin({
created() {
if (this.$options.rules) {
// TODO
Object.keys(this.$options.rules).forEach(key => {
// 保存rules的foo对象规则
const rule = this.$options.rules[key]
// 监听data中foo的变化
this.$watch(key, (newValue) => {
// 调用foo.validate对应的方法
const result = rule.validate(newValue)
if (!result) {
console.log(rule.message);
}
})
})
}
},
})
}
}
// 注册使用插件
Vue.use(RulesPlugin)
测试代码
const vm = new Vue({
data: { foo: 10 },
rules: {
foo: {
validate: value => value > 1,
message: 'foo must be greater than one'
}
}
})
vm.foo = 0 // should log: "foo must be greater than one"
这一节主要学的内容就是:
- 了解编写插件的流程,Vue.use()–>install()–>Vue.mixin()–>created()周期–>this.$option访问实例的配置项
- 根据配置项目数据,使用Vue的watch监听,实现一个简单的验证功能
在这里我回忆起了我在vue3+ts中自定义组件库的方法
// .vue文件同级目录的index.js
import { App } from 'vue'
import chooseArea from './chooseArea.vue'
// 让这个组件可以以use的形式使用
export default {
install(app: App) {
app.component('mk-choose-area', chooseArea)
},
}
// 所有组件总目录的index.js
import { App } from 'vue'
import ChooseArea from './chooseArea'
const components = [
ChooseArea
]
export default {
install(app: App) {
components.map((item) => {
app.use(item)
})
},
}
调用app.use(plugin)
,前面的install函数会被执行