如何在Vue实例中使用Global Mixin方法

问题描述 投票:0回答:1

假设我有以下情况,使用Global Mixin使用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”调用mixin方法“replaceString”?我试图使用“vm.replaceString”,但不断返回“undefined”。

javascript vue.js vuejs2 vue-mixin
1个回答
0
投票

我认为这个代码是您正在寻找的:

var mixin = {
methods: {
foo: function () {
  console.log('foo')
},
   conflicting: function () {
      console.log('from mixin')
   }
 }
}

var vm = new Vue({
  mixins: [mixin],
methods: {
  bar: function () {
  console.log('bar')
  },
    conflicting: function () {
      console.log('from self')
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

来自docs

© www.soinside.com 2019 - 2024. All rights reserved.