本文介紹如何在vue中定義插件,注冊(cè)插件和使用插件
插件目錄
/src/plugins
插件入口文件
/src/plugins/index.js
import cache from './cache'
import modal from './modal'
// 安裝默認(rèn)插件,在main.js中引入,通過Vue.use()使用它,因?yàn)閕ndex.js里使用export default導(dǎo)出,所有在main.js里導(dǎo)入時(shí)可以不用加{},直接import plugins from "~/plugins";
export default {
install(Vue) {
// 緩存對(duì)象
Vue.prototype.$cache = cache
// 模態(tài)框?qū)ο?,在vue頁面中使用this.$modal.xxx()調(diào)用
Vue.prototype.$modal = modal
}
}
注冊(cè)全局插件
/src/main.js文章來源:http://www.zghlxwxcb.cn/news/detail-710494.html
import plugins from "~/plugins";
Vue.use(plugins)
vue文件中使用插件
注意在其它js中還是需要手動(dòng)引用插件的,這個(gè)main.js中的注冊(cè),只有vue文件有效.文章來源地址http://www.zghlxwxcb.cn/news/detail-710494.html
<el-button @click="alertTest">全局插件</el-button>
<script>
export default {
methods: {
alertTest() {
this.$modal.confirm("不用在vue顯示引用plugins/modal.js,它通過在plugins/index.js中引用,在main.js中注冊(cè),已經(jīng)是全局的了");
}
}
}
</script>
注冊(cè)全局方法
- 還是在上面的/src/main.js中進(jìn)行添加prototype的定義
- 從插件中引入一個(gè)方法addDateRange
import { addDateRange } from "@/utils/ruoyi";
- 在prototype中添加原型擴(kuò)展方法
Vue.prototype.addDateRange = addDateRange
- 下面我們可以在view中直接使用這個(gè)addDateRange方法了,而不需要再import引入它了。
到了這里,關(guān)于vue~全局插件和全局方法的注冊(cè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!