繁体   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