簡體   English   中英

如何在 Vue 中更改道具時調用 Axios?

[英]How do I call Axios on prop change in Vue?

在更改值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'))
      } 
}`

您可以使用watch收聽id道具更改:

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

這是一個基於您共享的代碼的小演示,它顯示了watch如何對id prop 更改做出反應。 下面的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM