Vue:如何等到一种方法完成后再触发另一种方法

Ash*_*own 5 javascript vue.js

我的 Vue 实例有两种方法;

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
 this.getId()
 this.foo()
 }
})
Run Code Online (Sandbox Code Playgroud)

console.log()日志null作为值,因为它在响应getId()设法设置id值之前运行。我知道这一点是因为当我使用 Vue 开发人员工具时, id 是我期望的实际值而不是null.

如何确保getId()在运行前设置了值this.foo()

Hus*_*him 6

您可以使用 JavaScript Promise 来实现这一点。最简单的方法是使用 async/await 语法..

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: async function() {
   await this.getId()
   this.foo()
 }
})
Run Code Online (Sandbox Code Playgroud)

或者你可以走老式的路..

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
   this.getId().then(() => this.foo())
 }
})
Run Code Online (Sandbox Code Playgroud)