插件的定义和使用
-
插件通常用来为
Vue
添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:- 添加全局方法或者 property。如
vue-custom-element
- 添加全局资源:指令/过滤器/过渡等。如
vue-touch
- 通过全局混入来添加一些组件选项。如
vue-router
- 添加全局实例方法,通过把它们添加到
config.globalProperties
上实现 - 一个库,提供自己的
API
,同时提供上面提到的一个或多个功能。如vue-router
- 添加全局方法或者 property。如
-
使用插件
import { createApp } from 'vue'
import Root from './App.vue'
import i18nPlugin from './plugins/i18n'
const app = createApp(Root)
const i18nStrings = {
greetings: {
hi: 'Hallo!'
}
}
app.use(i18nPlugin, i18nStrings)
app.mount('#app')
- 开发插件
const myPlugin = {
install(app, options) {
app.provide('name', '李四')
app.directive('focus', (el, bind) => {
el.focus()
})
app.mixin({
created() {
// 执行两次
console.log('I am mixin');
}
})
app.config.globalProperties.$sayHello = 'hello world'
}
}
const app = Vue.createApp({
template: `<my-title />`
})
app.component('my-title', {
inject: [ 'name' ],
mounted() {
console.log(this.$sayHello)
},
template: `<div> {{ name }} <input v-focus /></div>`
})
app.use(myPlugin, { name: '张三' })
app.mount('#root')
数据校验插件开发实例
const validatorPlugin = (app, options) => {
app.mixin({
created() {
for (const key in this.$options.rules) {
if (this.$options.rules.hasOwnProperty(key)) {
const item = this.$options.rules[key]
this.$watch(key, value => !item.validata(value) && console.log(item.message))
}
}
}
})
}
const app = Vue.createApp({
data() {
return {
name: '张三',
age: 12,
}
},
template: `
<div>name: <input v-model="name" /></div>
<div>age: <input type="number" v-model="age" /></div>
`,
rules: {
name: {
validata: name => name && name.length >= 4,
message: 'name too short',
},
age: {
validata: age => age >= 16,
message: 'too young, to simple',
}
},
})
网友评论