代码之家  ›  专栏  ›  技术社区  ›  wbdlc

Axios Get API调用导致意外行为

  •  1
  • wbdlc  · 技术社区  · 7 年前

    代码笔: https://codepen.io/anon/pen/XxNORW?editors=0001

    info:[
    {
        "id": 1,
        "title": "Title one",
        "category_data": {
            "2": "Team",
            "7": "Queries"
        }
    }
    ],
    

    问题:

    全部 其余的不是

    mounted() {
       this.getData(); 
    },
    methods: {
        getData: function() {
          axios
           .get('https://EXAMPLE.com/API/')
          .then(response => {
            this.info = response.data
            this.dataReady = true
          })
          .catch(error => {
            console.log(error)
           this.errored = true
      })
           .finally(() => this.loading = false)
        }
    },
    

    我怎样才能解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  1
  •   tony19 thanksd    7 年前

    在你的演示中,呼叫 select() getData() 解决了,所以就走吧 选择() 获取数据()

    async mounted() {
      await this.getData();
      this.select();
    },
    methods: {
      async getData() {
        const {data} = await axios.get(/* URL TO API DATA */);
        this.info = data;
      },
      // ...
    }
    

    demo

        2
  •  0
  •   Surya Neupane    7 年前

    轴心 在你的 vue公司 应用程序中,您正在内部使用“this”关键字 轴心 这使得编译器很难理解您要引用的对象 或vue,因此要解决此问题,请尝试以下代码:

    getData: function() {
       let app = this;
      axios
       .get('https://EXAMPLE.com/API/')
      .then(response => {
        app.info = response.data
        app.dataReady = true
      })
      .catch(error => {
        console.log(error)
       app.errored = true
      })
       .finally(() => app.loading = false)
      }
    

    希望这能解决你的问题。