通常我们向Vue全局添加一些功能时,会采用插件的模式,它有两种编写方式:
- 对象类型:一个对象,但是必须包含一个install 的函数,该函数会在安装插件时执行;
- 函数类型:一个function,这个函数会在安装插件时自动执行;
插件可以完成的功能没有限制,比如下面的几种都是可以的:
- 添加全局方法或者 property,通过把它们添加到 config.globalProperties 上实现;
- 添加全局资源:指令/过滤器/过渡等:
- 通过全局 mixin 来添加一些组件选项
- 一个库,提供自己的 API,同时提供上面提到的一个或多个功能:
示例代码
// App.vue
<template>
<div class="app">
<h2>app</h2>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
// 安装插件
// 方式一: 传入对象的情况
app.use({
install: function(app) {
console.log("传入对象的install被执行:", app)
}
})
// 方式二: 传入函数的情况
app.use(function(app) {
console.log("传入函数被执行:", app)
})
我们在main.js中用.use来使用插件
import { createApp } from 'vue'
import App from './03_安装插件/App.vue'
import useDirectives from './01_自定义指令/directives/index'
const app = createApp(App);
// 自定义指令方式一:
// useDirectives(app)
// 自定义指令的方式二:使用插件
app.use(useDirectives)
app.mount('#app')
感谢大家观看,我们下次见
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。
I've learn several good stuff here. Certainly price bookmarking for revisiting. I surprise how so much effort you put to make such a great informative website.
It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.