插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码。
一个插件可以是一个拥有 install() 方法的对象,也可以直接是一个安装函数本身。
export default {
install: (app :any, options: any) => {
// 提供一个全局方法
app.config.globalProperties.$Alert = (val:any) => {
alert(`我是弹出的内容 ${val}`)
}
// 提供一个全局属性
app.config.globalProperties.$Info = {
code: 200,
msg: "数据接收"
}
// 通过provide 注册一个全局属性
app.provide('$MyInfo',{
data: "provide 提供的数据"
})
// 提供一个全局指令
app.directive('format-data', {
/* ... */
})
}
}
一般注册全局组件这样写。
import componentA from "../package/componentA"; // 引入封装好的组件
....
const componentList = [componentA,componentB,componentC,]; // 将来如果有其它组件,都可以写到这个数组里
// 批量组件注册
const install = function (Vue) {
componentList.forEach((com) => {
Vue.component(com.name, com);
});
};
export default install; // 这个方法以后再使用的时候可以被use调用
<!---->
<!---->
<!---->
当编写插件完时,我们需要使用时,我们可以在入口文件中,引入插件,然后通过 Vue.use() 注册使用 该插件。 插件内部暴露了一个 install 方法, Vue 会执行该方法去安装注册(指令,组件,全局属性等)
注册插件
import myPlugin from "./plugins/utils/index.js"
const app = createApp(App)
app.use(myPlugin)
app.use(router)
app.mount('#app')
在组件中使用插件
<!---->
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
console.log(proxy, proxy.$Test())
const { $Alert,$Info } = getCurrentInstance().appContext.config.globalProperties
//使用插件提供的方法和属性
const getData = () => {
console.log($Info)
console.log(myInfo)
$Alert("测试")
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。