如何实现一个vue的自定义插件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
// plugin 插件, 也是把通用性的功能封装起来
const myPlugin = {
install(app, options) {
app.provide('name', 'Dell Lee'); // 1、注入一个name
app.directive('focus', { // 编写指令
mounted(el) {
el.focus();
}
})
app.mixin({
mounted(){
console.log('mixin')
}
})
// 4、vue全局属性配置 做一些扩展 $ 表示扩展一个私有的内容 对Vue的底层做一些扩展
app.config.globalProperties.$sayHello = 'hello world'; // 编写
}
}
const app = Vue.createApp({
template: `
<my-title />
`
});
app.component('my-title', {
inject: ['name'], // 2、获取name
mounted() {
console.log(this.$sayHello); // 5、获取扩展的vue的私有属性
}, // 3、使用 name
template: `<div>{{name}}<input v-focus /></div>` // 使用指令
})
app.use(myPlugin, { name: 'dell'});
const vm = app.mount('#root');
</script>
</html>
实现一个做数据校验的插件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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 { name: 'dell', age: 23}
},
rules: {
age: {
validate: age => age > 25,
message: 'too young, to simple'
},
name: {
validate: name => name.length >= 4,
message: 'name too short'
}
},
template: `
<div>name:{{name}}, age:{{age}}</div>
`
});
const validatorPlugin = (app, options) => {
app.mixin({
created() {
for(let key in this.$options.rules) {
const item = this.$options.rules[key];
this.$watch(key, (value) => {
const result = item.validate(value);
if(!result) console.log(item.message);
})
}
}
})
}
app.use(validatorPlugin);
const vm = app.mount('#root');
</script>
</html>
vue-插件-编写-use - 简书
Vue 插件编写_vue插件怎么写_叶公子star的博客-CSDN博客