gpt4 book ai didi

javascript - 在Vue中调用插件方法

转载 作者:行者123 更新时间:2023-12-03 07:56:14 24 4
gpt4 key购买 nike

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

  • 我想检查某些按钮是否正常工作。所以如果他们不喜欢
    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>

    最佳答案

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

    关于javascript - 在Vue中调用插件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64927555/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com