vue插件的定义和使用
定义:
const 插件名 = {
install(app, options) {
// 内容
}
}
// 或者如下方式定义
const 插件名 = (app, options) => {
// 内容
}
使用:
vue实例名.use(插件名, {数据键值对})
// 没有传数据可以不写第二个参数
vue实例名.use(插件名)
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>插件的定义和使用</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 插件定义
const myPlugin = {
install(app, options) {
// 数据传递 provide
app.provide('name', '国王排名')
// 自定义指令 directive
app.directive('hello', {
mounted(el) {
console.log(el)
console.log(options)
alert('我是' + options.uname + ',很开心认识你!')
// el.value = 'hello'
}
})
// 混入 mixin
app.mixin({
mounted() {
alert('你好呀波吉王子,我是卡克')
}
})
}
}
const app = Vue.createApp({
// 数据接收 inject
inject: ['name'],
template: `
<div>{{ name }}</div>
<div v-hello></div>
`
})
// 插件使用 use
app.use(myPlugin, {uname: '波吉'})
const vm = app.mount('#root')
</script>
</html>
页面效果:
简单数据校验插件示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据开发插件开发</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
age: 5,
uname: '史迪仔'
}
},
rules: {
age: {
validate: age => age > 10,
message: '还很小哦,努力长大吧'
},
uname: {
validate: uname => uname.length > 2,
message: '名字需要2个字及以上'
}
},
template: `
<div>名字:{{uname}}- - -年龄:{{age}}</div>
`
})
// 插件定义
const myPlugin = (app, options) => {
app.mixin({
created() {
// console.log(this.$options.rules)
for(let key in this.$options.rules) {
const item = this.$options.rules[key]
this.$watch(key, (value) => {
const res = item.validate(value)
if(!res) {
console.log(item.message)
}
})
}
}
})
}
// 插件使用
app.use(myPlugin)
const vm = app.mount('#root')
</script>
</html>
页面控制台修改数据测试结果: