Как мне позвонить Аксиосу о смене реквизита в Vue? - PullRequest
0 голосов
/ 12 января 2019

При изменении значения id я хотел бы сделать вызов JSON через Axios и обновить необходимые части страницы. Как я могу это сделать? В настоящее время у меня есть mounted и activated, и они, кажется, не работают ...

Код:

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 голосов
/ 12 января 2019

Вы можете прослушать id смену реквизита, используя watch :

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

Вот небольшая демонстрация, основанная на коде, которым вы поделились, который показывает, как watch реагирует на id изменение реквизита. Компонент 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...