vue中调用插件方法

Invoke plugin method in vue

我想实现一个插件,我在其中定义了一个抛出错误的方法。该方法将用于不同的组件。例如,如果单击按钮或给定值 <0。我在 App.vue.

试过了

现在我无法调用 App.vue 中的方法,我不太确定。

我的插件:

  const throwingError = {}
  throwingError.install = function (Vue){
  Vue.mixin({
  LogEvent(value, msg){
    try {
      if(event){
        throw new Error(msg)
      }
    } catch (error) {
        console.error("Error Message": error.message)
              }
            }
         });
       }

   export default throwingError

在我的 main.js 中,我导入了插件

import throwingError from "./plugin/throwingError
Vue.use(throwingError)

我的App.vue:

   <template>
    <div id="app">
     <button v-on:click="LogEvent($event, 'hi')">
      Click to trigger throwingError method
     </button>
     </div>
    </template>
     <script>
          import throwingError from './plugins/throwingError'
          export default{
          mounted() {
           throwingError(event, "test")
          },
       };
     </script>

由于您的插件创建了一个 mixin,因此您不需要将插件导入到您的组件中,而且通常您不会对任何插件这样做。但是有一些语法错误和缺少 methods 选项。试试这个:

const throwingError = {}
throwingError.install = function (Vue){
  Vue.mixin({
    methods: {  // You missed this, `LogEvent` is a method
      LogEvent(event, msg){  // This had a wrong argument name
        try {
          if(event){
            throw new Error(msg)
          }
        } catch (error) {
          console.error("Error Message:", error.message); // This syntax was wrong
        }
      }
    }
  });
}
Vue.use(throwingError);

/***** APP *****/
new Vue({
  el: "#app",
  mounted() {
    this.LogEvent({}, 'test'); // This was missing the method name
  }
});

Vue.config.productionTip = false;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button v-on:click="LogEvent($event, 'hi')">
    Click to trigger throwingError method
  </button>
</div>