代码之家  ›  专栏  ›  技术社区  ›  revy

Vuex提交不会触发v-show

  •  0
  • revy  · 技术社区  · 7 年前

    我正在努力 vuex 我第一次发现 v-show 在存储区上提交变异后未触发指令

    // store.js
    import Vue from "vue"
    import Vuex from "vuex"
    
    const states = {
        app: {
            init: "APP_INIT"
        }
    }
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
        state: {
            appState: ""
        },
        mutations: {
            changeAppState (state, appState) {
                state.appState = appState
            }
        },
        getters: {
            isVisible: state => state.appState === states.app.init
        }
    })
    export { store }
    

    成分a。vue

    <template v-show="isVisible">
        <div id="componentA"></div>
    </template>
    
    <script>
        export default {
            name: "ComponentA",
            computed: {
                isVisible () {
                    return this.$store.getters.isVisible
                },
                appState () {
                    return this.$store.state.appState
                }
            },
            watch: {
                appState (newVal, oldVal) {
                    console.log(`Changed state: ${oldVal} => ${newVal}`)
                }
            },
            mounted () {
                setTimeout(() => {
                    this.$store.commit("changeAppState", "APP_INIT")
                }, 1000)
            }
        }
    </script>
    
    <style scoped lang="scss">
        #componentA {
            width: 400px;
            height: 400px;
            background: red;
        }
    </style>
    

    我定义了一个 getter isVisible 应该评估哪一个 true 如果 state.appState 属性等于字符串 APP_INIT . 我认为对突变的提交将触发反应系统并强制重新呈现视图,但这并没有发生。为什么?

    0 回复  |  直到 7 年前
        1
  •  2
  •   tony19 thanksd    7 年前

    指令不能应用于根目录 <template> 像那样。您必须使用一个内部元素:

    <template>
      <div v-show="isVisible">
        ...
      </div>
    </template>
    

    demo

    还要注意Vue docs 声明:

    注意 v-show 不支持 <模板> 元素,也不适用于 v-else .

    推荐文章