【问题标题】:Call Mixin global method from Vuex从 Vuex 调用 Mixin 全局方法
【发布时间】:2019-03-08 00:46:33
【问题描述】:

我有一个这样的mixin,带有一个请求方法来调用axios和处理错误等:

import Vue from 'vue'
import axios from 'axios';
    
Vue.mixin({
    methods: {
        request(url, datas) {

        //Call axios and return premise
        [...]
    }
});

我有一个这样的商店:

const actions = {
    selectEmployees: (store, keywords) => {
        this.request(`/users/list/search{/keywords}`).then(e => {
            store.commit('SELECT_EMPLOYEES', e.data)
        });
    }
}
    
let store = new Vuex.Store({
    state: state,
    mutations: mutations,
    getters: getters,
    actions: actions
})

我想用 request 来调用 axios 却出现这个错误:

挂载钩子中的错误:“TypeError:无法读取属性‘请求’的 undefined" TypeError: 无法读取未定义的属性 'request'

【问题讨论】:

  • 能否提供main.js的代码?

标签: vue.js vuejs2 vuex


【解决方案1】:

docs 所述,Mixins 用于组件。 Vuex 本身并不是一个组件。正如我所看到的,您正在使用新的导入/导出工作方式,只需将您的混音设置为导出的简单功能即可。然后在其他地方要么将它们作为 mixin 附加到 Vue,要么在商店外部使用它。大体上的东西(半代码):

// mixin.js
export default function request() {}

// main.js
Vue.mixin({
    methods: {
        request: mixin.request // will provide this.request in each component
    }
}

// store.js
mixin.request() // will fire the method

【讨论】:

  • 你如何获得 store.js 中的 mixin? ?
  • 作为import mixin from './wherever/the/file/is';
  • 如果我想从 vue 实例中调用 Global Mixin? vm = new Vue()vm.mixinMethod()??
  • 在这种情况下,如果您import mixin from './wherever/the/file/is';,那么您不能按照上面的建议执行mixin.request(),而是将其称为mixin() 来触发该函数。
  • 您将 main.js 命名为 mixin 实例化的文件,并将 mixin.js 命名为共享函数所在的文件。应该是反的吧?不是很清楚……
【解决方案2】:

由于请求方法在mixin的方法obj中

// store.js 
import mixin from './mixin'

// access mixin method
mixin.methods.request()

【讨论】:

  • 不确定最佳实践之类的,但这就像一个魅力
  • 这违背了 mixins 的目的。
  • 访问方法的方式对我来说也非常好用,但是无法从 store.js 访问 mixin.js 的 $data 变量。你能帮帮我吗?
  • @Emobe 你能详细说明为什么这会违背 mixins 的目的并提供一个没有的解决方案吗?
  • @Michael Mixins 将在组件的 mixin 属性中使用。这本质上只是一个帮助程序/实用程序。
【解决方案3】:

我的解决方案:

//GlobalMixin.js
const Mixin = {
  methods: {
    _secureHTML(str) {
      return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }
  }
}

export { Mixin } //use: import { Mixin } from 'GlobalMixin.js'

// - export it as a Vue Plugin
export default {
  install(Vue, options) {
    Vue.mixin(Mixin)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2016-07-29
    • 2020-02-07
    • 2021-07-27
    相关资源
    最近更新 更多