自定义指令可以实现:1、自定义全局组件2、自定义全局指令3、添加全局的属性和方法4、全局依赖注入
实现过程如下:
首先在项目的src目录下新建一个plugins目录用于存放所有自定义插件文件,如图:
接着我们在plugins目录下新建自己的插件文件,例如这里是要建一个loading插件,在loading.js文件中去写loading的逻辑代码:
export default {
install(app, config) {
//在这里写插件的逻辑
console.log("插件创建成功了")
}
}
然后在main.js中全局注册插件
import { createApp } from 'vue'
import App from './App.vue'
//引入插件
import loading from './plugins/loading'
const app = createApp(App)
//使用插件
app.use(loading)
app.mount('#app')
下面分别介绍插件可以实现的四种功能:
1、自定义全局组件,以单文件组件的形式引入
import LoadingPage from './LoadingPage'
export default {
install(app) {
//自定义全局组件
app.component('LoadingPage', LoadingPage)
//自定义全局指令
app.directive('focus', {
mounted(el) {
el.focus()
}
})
//自定义全局属性
app.config.globalProperties.$xxx = '全局自定义属性1'
//全局依赖注入
app.provide('xxx', '全局依赖注入')
}
}
在组件中使用
<template>
<div>
首页
<LoadingPage />
<input type="text" v-focus>
{{xxx}}
</div>
</template>
<script>
export default {
inject: ['xxx'],
name: 'HomePage',
mounted() {
console.log(this.$xxx)
}
}
</script>