简体   繁体   English

Vue组件在状态更改时未更新

[英]Vue component not updating on state change

<div v-for="(photon, key) in $store.state.notConnected" v-bind:key="key">
    <div v-if="!photon.connected">
        <p>Photon is not Connected</p>
    </div>
    <div v-if="photon.connected">
        <p>Photon is Connected</p>
        <b-btn v-on:click="showNewSetup(photon)>Setup</b-btn>
    </div>
    <div v-if="photon.showSetup">Setup Page</div>
</div>    

Store.js Store.js

export const store = new Vuex.store({
 state:{
   notConnected:{}
 },
 mutations:{
 setDevices(state,value){
 value.data.forEach(ele =>{
 state.notConnected[ele.id]={}
 state.notConnected[ele.id].showSetup=false
 state.notConnected[ele.id].connected=ele.connected
 }
 },
 SHOWNEWSETUP(state,value){
  state.notConnected[value.id].showSetup=true
}}
actions:{
async getDevices(context){
let devices = await axios.get('http:10.10.10.1:3000/api')
context.commit('setDevices',devices)
}
}
})

I'm mutating the state in my vuex store but the v-if doesn't reflect the updated state. 我正在vuex存储中更改状态,但v-if不能反映更新后的状态。 When I open up vue dev tools I see the mutation happen and can see that the state has changed, but the setup page div isn't updating. 当我打开vue dev工具时,我看到突变发生了,并且可以看到状态发生了变化,但是安装页面div没有更新。

Note: If i go to a diffrent route and go back to the page the component updates 注意:如果我转到其他路线并返回页面,组件将更新

Vue has no chance to detect changes in Arrays (except vue3 with proxy support). Vue没有机会检测阵列中的更改(具有代理支持的vue3除外)。

That's why you should alter your mutation to: 这就是为什么您应该将突变更改为:

SHOWNEWSETUP(state,value){
  Vue.set(state.notConnected, value.id, {showSetup=true})
}

That way Vue's reactivity system is informed about the change and everything should work as expected. 这样一来,Vue的反应系统就可以了解更改,一切都将按预期工作。

Try using a computed property in your component instead of pointing to state directly: 尝试在组件中使用计算属性,而不是直接指向状态:

<template>
    <div v-for="(photon, key) in photons v-bind:key="key">
        <div v-if="!photon.connected">
            <p>Photon is not Connected</p>
    </div>
    <div v-if="photon.connected">
        <p>Photon is Connected</p>
        <b-btn v-on:click="showNewSetup(photon)>Setup</b-btn>
    </div>
        <div v-if="photon.showSetup">Setup Page</div>
    </div>   
</template>

<script>
    computed: {
        photons() {
            return this.$store.state.notConnected
        },
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM