2

Vue2自定义插件的写法-Vue.use() - 云冬

 1 year ago
source link: https://www.cnblogs.com/008ts/p/16409959.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vue2自定义插件的写法-Vue.use()

    最近在用vue2完善一个项目,顺便温习下vue2的基础知识点!

有些知识点恰好没用到时间一长就会淡忘,这样对自己是一种损失。

 定义一个对象 对象里可以有任何内容 但install的函数是必不可少的,因为 use方法会去调用target.install();

  值得一提的是这里调用install的时候会向这个函数传入Vue实例(刚出生的时候,或者叫 beforeCreate钩子时期的实例),这就给了我们很多的操作空间!

  我们知道不管是搞全局事件总线还是怎样都是往Vue原型上挂方法,这里就可以利用它来封装属于自己的Vue插件;

 Vue.use()其实还有第二个参数,可以是一个对象,可以传入自己diy的内容,让Vue变得更加华丽!、

  下边看我写的示例吧;

myplgins.js<br><br>------------------<br><br>import axios from "@/utils/network";
const myPlugins = {};
myPlugins.install = function (Vue, {a, b, c}) {
Vue.config.productionTip = false;
Vue.config.devtools = true
Vue.prototype.$bus=Vue //将一个全新的vue实例当作一个共有对象 全局事件总线
Vue.prototype.axios=axios
}
export default myPlugins
main.js<br>
---------------------
import myPlugins from '@/utils/testPlugins'
Vue.use(myPlugins, {a: 1, b: 2, c: 3})

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK