如何在Vue中更改道具时调用Axios? [英] How do I call Axios on prop change in Vue?

查看:34
本文介绍了如何在Vue中更改道具时调用Axios?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于值 id 的更改,我想通过Axios进行JSON调用并更新页面的必要部分.我怎么做?目前,我已 mount activated ,它们似乎无法正常工作...

On the change of the value id, I would like to make a JSON call via Axios and update necessary parts of the page. How do I do that? Currently, I have mounted and activated and they do not seem to be working...

代码:

const Home = { 
    template: `

    <div class="user">
        <h2>user {{ id }}</h2>
        <h2>{{ info }}</h2>
        bet
    </div>

    `,
    props: {
        id: {
            type:    String,
            default: 'N/A'
        }
    },
    data () {
        return {
          info: null
        }
      },
    activated () {
        axios
          .get('https://api.coindesk.com/v1/bpi/currentprice.json', 
          { params: { id: id }}
          )
          .then(response => (this.info = response))
      }, 

      mounted() {
        axios
          .get('https://api.coindesk.com/v1/bpi/currentprice.json')
          .then(response => (this.info = 'response'))
      } 
}`

推荐答案

您可以使用


这是一个基于您共享的代码的演示,展示了 watch id 属性更改的反应.以下 Wrapper 组件仅用于演示目的,因为它会触发 id 值更改.


Here is a little demo based on the code that you shared that shows how watch reacts to id prop change. Wrapper component below is solely for demonstration purpose as something that triggers id value change.

const Home = {
  template: `

    <div class="user">
        <h2>user {{ id }}</h2>
        <h2>{{ info }}</h2>
        bet
    </div>

    `,
  props: {
    id: {
      default: 'N/A'
    }
  },
  data () {
    return {
      info: null
    }
  },
  mounted() {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = 'response'))
  },
  watch: {
    id: function(newId) {
      console.log(`watch triggered, value of id is: ${newId}`);
      axios
        .get('https://api.coindesk.com/v1/bpi/currentprice.json',
          { params: { id: newId }}
        )
        .then(response => (this.info = response))
    }
  }
}

const Wrapper = {
  template: '<div><home :id="id" /></div>',
  components: { Home },
  data() {
     return {
        id: 0
     }
  },
  mounted() {
     const limit = 5;
     const loop = (nextId) => setTimeout(() => {
       console.log(`#${nextId} loop iteration`);
       if (nextId < limit) {
          this.id = nextId;
          loop(nextId + 1);
       }
     }, 3000);
     loop(this.id);
  }
}

new Vue({
  el: '#app',
  components: { Wrapper }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js" ></script>
<div id="app">
<wrapper />
</div>

这篇关于如何在Vue中更改道具时调用Axios?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆