【问题标题】:VueJS plugins conflictVueJS 插件冲突
【发布时间】:2020-07-14 01:02:46
【问题描述】:

我在由 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;

authentication.vue

import Vue from "vue";

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

Vue.use(Plugin);

export default Plugin;

ma​​in.js

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

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

instructions.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 插件未激活

那么我怎样才能让它们同时工作呢?

【问题讨论】:

  • 这看起来很混乱。你的Vue.use() 电话加倍。此外,Plugin 从未在您的任何代码中定义,您为什么要在单个文件 .vue 组件中定义插件?
  • 因为这是文档中关于创建 Vue 插件的内容。 vuejs.org/v2/guide/plugins.html
  • 对,对。这些不是最全面的说明。如果您有动力,您可以随时提出文档问题。
  • 我一定会的.. 这会帮助很多人

标签: vuejs2 vue-cli-4


【解决方案1】:

也许尝试使用以下方法稍微简化一下?

// 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)
})

【讨论】:

猜你喜欢
  • 2015-07-14
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多