【问题标题】:Invoke plugin method in vue在 vue 中调用插件方法
【发布时间】:2020-11-20 10:13:02
【问题描述】:

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

  • 我想检查一些按钮是否正常工作。所以如果他们不是,比如 if(!event){ throwingError("msg")}
  • 我还打算与错误抛出进行一些价值比较

现在我无法调用 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>

【问题讨论】:

    标签: javascript vue.js plugins error-handling


    【解决方案1】:

    由于您的插件创建了一个 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>

    【讨论】:

    • 谢谢你的回答,丹!经过一些小改动后,它对我有用。我的插件声明了一些全局方法。在我尝试了您推荐的方式后,它停止了工作。解决方案是只导出整个插件。在 main.js 我必须导入和编写 Vue.use(plugin)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2020-09-01
    • 2021-07-20
    • 1970-01-01
    • 2021-03-29
    • 2019-11-11
    相关资源
    最近更新 更多