如何在Vue中更改道具时调用Axios?

时间:2019-01-12 17:41:34

标签: javascript vue.js axios

关于值id的更改,我想通过Axios进行JSON调用并更新页面的必要部分。我怎么做?目前,我有mountedactivated,它们似乎没有用...

代码:

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 个答案:

答案 0 :(得分:0)

您可以使用watch来收听id道具变更:

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

这是一个基于您共享的代码的小演示,该代码演示watchid道具更改的反应。下面的Wrapper组件仅用于演示目的,可以触发id的值更改。

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>