5

我在由 Vue CLI 4 提供支持的 VueJS 应用程序中创建了两个插件,但是当我尝试在我的页面中使用它时,只有一个可以工作

| plugins
|-- axios.vue
|-- authentication.vue

axios.vue

import Vue from "vue";

Plugin.install = function(Vue) {
  Vue.prototype.$myName = "Dean Armada";
};

Vue.use(Plugin);

export default Plugin;

身份验证.vue

import Vue from "vue";

Plugin.install = function(Vue) {
  Vue.prototype.$name = "Chris Guinto";
};

Vue.use(Plugin);

export default Plugin;

main.js

import axios from "./plugins/axios.js";
import authentication from "./plugins/authentication.js";

Vue.use(axios);
Vue.use(authentication);

指令.vue

<template>
  <div>
      Hello World
  </div>
</template>

<script>
  export default {
    created() {
      console.log(this.$name);
      console.log(this.$myName);
    }
  }
</script>

<style lang="scss" scoped>

</style>

记笔记

  • 上面的输出将仅为“Dean Armada”并且console.log(this.$name)未定义
  • 但是,如果我注释掉了Vue.use(axios)console.log(this.$name)起作用,那么输出将是“Chris Guinto”,而另一个是未定义的,因为axios插件没有被激活

那么如何让它们同时工作呢?

4

1 回答 1

5

也许尝试使用以下方法对其进行一些简化?

// plugins/axios.js
export default {
    install(Vue){   
        Vue.prototype.$myname = "Dean Armada";
    }
}

// plugins/authentication.js
export default {
    install(Vue){   
        Vue.prototype.$name = "Chris Guinto";
    }
}

// main.js
import axios from "./plugins/axios.js";
import authentication from "./plugins/authentication.js";

Vue.use(axios);
Vue.use(authentication);

new Vue({
  el: '#app',
  render: h => h(App)
})
于 2020-04-02T06:18:19.543 回答