Vuejs axios 调用后变量赋值

alx*_*lxb 2 javascript vue.js axios vuejs2

我想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)

员工是“未定义的”。

我认为问题是异步或等待,但我不明白。

Ber*_*ert 6

看起来您希望 mixin 创建一个用于检索数据的通用方法。在这种情况下,您需要从方法返回承诺request并在成功回调中处理结果数据。

这是一个工作示例。

console.clear()

const EmployeesList = {
  name: "employees-list",
  template: `
      <ul>
        <li v-for="employee in employees">{{employee.title}}</li>
      </ul>
    `,
  data() {
    return {
      employees: []
    }
  },
  mounted() {
    // obviously using posts here as an example instead of 
    // employees.
    this.request('https://jsonplaceholder.typicode.com/posts')
      // handle the promise success
      .then(e => this.employees = e);
  }
}

Vue.mixin({
  methods: {
    request: function(url) {
      // return the promise
      return axios.get(url)
        .then(response => {
          return response.data
        })
        .catch(e => {
          this.errors.push(e)
        })
    }
  }
});

new Vue({
  el: "#app",
  components: {
    EmployeesList
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <employees-list></employees-list>
</div>
Run Code Online (Sandbox Code Playgroud)