[英]How do I call Axios on prop change in Vue?
On the change of the value id
, I would like to make a JSON call via Axios and update necessary parts of the page.在更改值id
时,我想通过 Axios 进行 JSON 调用并更新页面的必要部分。 How do I do that?我怎么做? Currently, I have mounted
and activated
and they do not seem to be working...目前,我已经mounted
并activated
,它们似乎没有工作......
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'))
}
}`
You can listen to id
prop change by using watch :您可以使用watch收听id
道具更改:
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.这是一个基于您共享的代码的小演示,它显示了watch
如何对id
prop 更改做出反应。 Wrapper
component below is solely for demonstration purpose as something that triggers id
value change.下面的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.