How do I call Axios on prop change in Vue?

一个人想着一个人 提交于 2021-01-28 15:30:34

问题


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...

Code:

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'))
      } 
}`

回答1:


You can listen to id prop change by using watch:

watch: {
  id: function(newId) {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json',
           { params: { id: newId }}
      )
      .then(response => (this.info = response))
  }
}

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>


来源:https://stackoverflow.com/questions/54162239/how-do-i-call-axios-on-prop-change-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!