<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>lesson 32</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
</style>
</head>
<body>
<div id="root"></div>
</body>
<script>
// plugin插件,也是把通用性的功能封装起来
const myPlugin = {
install(app, options) {
app.provide('name','Dell Lee');
app.directive('focus', {
mounted(el) {
el.focus();
}
});
app.mixin({
mounted() {
console.log('mixin');
}
});
app.config.globalProperties.$sayHello = 'hello world';
console.log(app, options);
}
};
const app = Vue.createApp({
template:
`<my-test />`
});
app.component('my-test',{
inject:['name'],
template:
`<h1>{{name}}</h1>
<input v-focus />
`
});
app.use(myPlugin, {name:'dell'});
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>lesson 33</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
</style>
</head>
<body>
<div id="root"></div>
<div id="hello"></div>
</body>
<script>
//对数据做校验的插件
const validatorPlugin = {
install(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)
});
}
}
});
}
}
const app = Vue.createApp({
data() {
return { name: 'dell', age:28 }
},
rules: {
age: {
validate:(age) => {return age > 25},
message: '太年轻了'
},
name: {
validate: name => name.length >= 4,
message: 'name too short'
}
},
template:
`<div>name:{{name}},age:{{age}}</div>`
});
// 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)
// });
// }
// // console.log(this.$options.rules);
// }
// });
app.use(validatorPlugin);
const vm = app.mount('#root');
</script>
</html>