调用后的Vuejs axios变量分配

Vuejs axios variable assignation after call

我想从混入中用 this.request(url) 调用 axios(以简化和集中有关 axios 的所有内容在同一个文件中),但它不起作用。

Vue 文件:

export default {
  name: "employees-list",
  data() {
    return {
      employees: []
    }
  },
  mounted() {
    this.employees = this.request('https://jsonplaceholder.typicode.com/posts');
  }
}

Request.js

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

员工是"undefined"。

我认为问题出在 async 或 await 上,但我不明白。

试试这个:

new Vue({
    el: '#root',
  data: {
    employees: []
  },
  methods: {
    request(url){
        return new Promise((resolve, _) => {
        axios.get(url)
          .then(res => {
            resolve(res);
          }).catch(err => {
            // err management
          });
      });   
    }
  },
  mounted(){
   this.request('https://jsonplaceholder.typicode.com/posts').then(res => {
    this.employees = res;
   })
  }
})

您似乎希望 mixin 创建一个通用方法来检索数据。在这种情况下,您需要 return 来自 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
  }
})
<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>