plugin插件
plugin插件是用来为 Vue 添加全局功能,把通用性的功能进行封装。
定义插件
定义插件需要使用 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象。
const myPlugin = {
install(app, options){
console.log(app, options);
}
}
使用插件
通过全局方法 Vue.use() 使用插件
pp.use(myPlugin,{name: '张三'})
打开控制台看看app, options分别会输出什么内容。
从图中可以看出,app包含有directive自定义指令、mixin混入以及config配置等内容,options里面是使用插件传入的{name: ‘张三’}。
添加directive
在plugin插件中添加directive。
const myPlugin = {
install(app, options){
app.directive("focus",{
mounted(el){
el.focus();
}
})
}
}
输入框获得焦点
添加mixin
在plugin插件中添加mixin。
const myPlugin = {
install(app, options){
app.mixin({
mounted(){
console.log('mixin');
}
})
}
}
控制台成功输出:mixin。
添加config
在plugin插件中添加config。
install(app, options){
app.config.globalProperties.$hello = 'hello';
}
}
然后在组件中调用hello,控制台成功打印出hello。
完整代码
<!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>Vue3 -- Plugin插件</title>
<!-- 使用CDN引入Vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
const myPlugin = {
install(app, options){
// console.log(app, options);
app.directive("focus",{
mounted(el){
el.focus();
}
})
// app.mixin({
// mounted(){
// console.log('mixin');
// }
// })
// app.config.globalProperties.$hello = 'hello';
}
}
const app = Vue.createApp({
mounted(){
console.log(this.$hello);
},
template:`
<div>
hello Vue.js!
<demo />
</div>`
});
app.use(myPlugin,{name: '张三'})
app.component('demo', {
template:`<input v-focus/>`
})
const vm = app.mount('#root');
</script>
</body>
</html>
总结
plugin插件:为 Vue 添加全局功能,包括但不限于directive、mixin、config等功能;
plugin插件的定义:使用 install 方法定义, install 方法有app, options两个参数;
plugin插件的使用:通过全局方法 Vue.use() 使用插件;
结语
本小节到此结束,谢谢大家的观看!
如有问题欢迎各位指正