gpt4 book ai didi

javascript - 如何使用 Vue 实例中的全局混合方法

转载 作者:行者123 更新时间:2023-11-30 19:48:33 26 4
gpt4 key购买 nike

假设我遇到以下情况,使用全局混合在 Vue 中创建全局辅助方法:

import Vue from "vue";

Vue.mixin({
methods: {
replaceString: function (word) {
return word.toLowerCase().replace(/\W/g, '');
}
}
});

let vm = new Vue({
methods: {
doSomething: function() {
console.log(this.replaceString('Hello World'); //helloword
}
}
});

我知道我可以在其他方法内部、组件及其子项内部调用该方法。但是如何从 Vue 实例“vm”调用混合方法“replaceString”?我尝试使用“vm.replaceString”,但一直返回“undefined”。

最佳答案

对您的代码进行少量更改并且可以正常工作:

  1. 你应该改变你的 mixin 的定义(var mixin 而不是 Vue.mixin)
  2. 将 mixin 导入您的新 vue 组件 (mixins = [mixin])

    import Vue from "vue";

    var mixin = {
    methods: {
    replaceString: function (word) {
    return word.toLowerCase().replace(/\W/g, '');
    }
    }
    };

    let vm = new Vue({
    mixins: [mixin]
    methods: {
    doSomething: function() {
    console.log(this.replaceString('Hello World'); //helloword
    }
    }
    });

关于javascript - 如何使用 Vue 实例中的全局混合方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54715799/

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