为什么数据元素在 Vuejs 中的某个函数中没有改变其值以及如何使其值可更改?



我在created((函数中的axios API的帮助下访问这些webURL。在 HTML 文件中,我通过鼠标悬停事件从某个 v-for 处理程序获取索引,并将索引的值分配给 selectedState 数据元素。但是,当我在控制台框中看到它时,它正在发生变化,但是当我将其用于某些功能时,它的值保持不变。

在这里,当我想将其用作webURL的数组索引(根据selectedState应该是动态的(时,statsJson属性的值保持不变。

var app = new Vue({
el: "#app",
data(){
return {
webURL:[{
id:0,URL:"https://raw.githubusercontent.com/smlab-niser/CRiAPGraph/master/districts/Andhra%20Pradesh.json?token=AOYHVJ22Y4JWLLUXWXODLRK6ZKARK"
},
{
id:22,URL:"https://raw.githubusercontent.com/smlab-niser/CRiAPGraph/master/districts/rajasthan.json?token=AOYHVJ575LRB2FOYBJMVKWK6ZKAVY"
},
{
id:3,URL:"https://raw.githubusercontent.com/smlab-niser/CRiAPGraph/master/states.json?token=AOYHVJ2BNIP7L3TMOE66JWK6ZKBRK"
}
],
selectedState:0,
cityJson: null,
statesJson: null
}},
methods:{
updateDetails:function(index, evt)
{
this.selectedState = index
console.log(this.selectedState)
console.log(this.statesJson.features[this.selectedState].id)
}
},

created () {
axios.all([axios.get('https://raw.githubusercontent.com/smlab-niser/CRiAPGraph/master/states.json?token=AOYHVJ2BNIP7L3TMOE66JWK6ZKBRK'),
axios.get(this.webURL[this.selectedState].URL)])
.then(axios.spread((user1,user2) => (
console.log(user1.data),
console.log(this.selectedState),
console.log(user2.data),
this.statesJson=user1.data,
this.cityJson=user2.data
)))
.catch(error => {
console.log(error)
})
},
})
<div id="app">
<div id="tooltip" display="none" style="position: absolute; display: none;"></div>
<svg id="svg" ref="svg" height="800" width="1600">
<path class="bar"
v-for="(state, index) in stateData"
:d="pathGenerator(state.feature)"
:style="{
fill: state.color,
stroke: 'darkslategray'
}"
@mouseover="updateDetails(index,state)"
@mouseout = "hideTooltip()"
>
</path>
</svg>
</div>

函数created()代码仅在创建 DOM 时和完全挂载之前触发一次。在这种情况下,selectedState将采用初始状态下定义的值 0。

更多关于 Vue 生命周期的信息可以在这里阅读 https://v2.vuejs.org/v2/guide/instance.html

当用户使用鼠标进行交互时,将调用updateDetails函数,该函数会更新selectedState,但是,它不会再次触发公理,这就是为什么statesJson的值保持不变的原因。您需要触发 axios 调用来更新statesJson

methods:{
updateDetails:function(index, evt)
{
this.selectedState = index;
this.axiosCall(); // trigger again
},
axiosCall() {
axios.all([axios.get('https://raw.githubusercontent.com/smlab-niser/CRiAPGraph/master/states.json?token=AOYHVJ2BNIP7L3TMOE66JWK6ZKBRK'),
axios.get(this.webURL[this.selectedState].URL)])
.then(axios.spread((user1,user2) => (
console.log(user1.data),
console.log(this.selectedState),
console.log(user2.data),
this.statesJson=user1.data,
this.cityJson=user2.data
)))
.catch(error => {
console.log(error)
})
},

created () {
this.axiosCall();
}

最新更新