我有一个像这样的 mixin 和一个请求方法来调用 axios 并处理错误等:
import Vue from 'vue'
import axios from 'axios';
Vue.mixin({
methods: {
request(url, datas) {
//Call axios and return premise
[...]
}
});
Run Code Online (Sandbox Code Playgroud)
我有一家这样的商店:
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
})
Run Code Online (Sandbox Code Playgroud)
我想使用 request 来调用 axios 但我有这个错误:
挂载钩子错误:“类型错误:无法读取未定义的属性‘请求’”类型错误:无法读取未定义的属性‘请求’
我想this.request(url)从 mixin 中调用 axios (以简化和集中有关 axios 的所有内容在同一个文件中),但它不起作用。
Vue 文件:
export default {
name: "employees-list",
data() {
return {
employees: []
}
},
mounted() {
this.employees = this.request('https://jsonplaceholder.typicode.com/posts');
}
}
Run Code Online (Sandbox Code Playgroud)
请求.js
Vue.mixin({
methods: {
request: function (url) {
axios.get(url)
.then(response => {
return response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
});
Run Code Online (Sandbox Code Playgroud)
员工是“未定义的”。
我认为问题是异步或等待,但我不明白。