plugin插件是用来为 Vue 添加全局功能,把通用性的功能进行封装。
定义插件需要使用 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象。
const myPlugin = {
install(app, options){
console.log(app, options);
}
}
通过全局方法 Vue.use() 使用插件
pp.use(myPlugin,{name: '张三'})
从图中可以看出,app包含有directive自定义指令、mixin混入以及config配置等内容,options里面是使用插件传入的{name: ‘张三’}。
在plugin插件中添加directive。
const myPlugin = {
install(app, options){
app.directive("focus",{
mounted(el){
el.focus();
}
})
}
}
在plugin插件中添加mixin。
const myPlugin = {
install(app, options){
app.mixin({
mounted(){
console.log('mixin');
}
})
}
}
控制台成功输出:mixin。
在plugin插件中添加config。
install(app, options){
app.config.globalProperties.$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>
<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:`
hello Vue.js!
`
});
app.use(myPlugin,{name: '张三'})
app.component('demo', {
template:``
})
const vm = app.mount('#root');
script>
body>
html>
plugin插件:为 Vue 添加全局功能,包括但不限于directive、mixin、config等功能;
plugin插件的定义:使用 install 方法定义, install 方法有app, options两个参数;
plugin插件的使用:通过全局方法 Vue.use() 使用插件;
结语
本小节到此结束,谢谢大家的观看!
如有问题欢迎各位指正