1

我使用 VueJs + VueX 构建 SPA,并且我在一个组件中单击“登录”和“注册”按钮,并<component></component>在其他组件中标记应该有条件地呈现 1 到模态(“注册”表单和“登录表单”) . 模态也是组件。
当我调用 console.log 时,我看到 state.currentView 会根据单击的按钮发生变化,但会检查 {{ $data | json }} 内部标记显示状态没有改变,更重要的是模态没有改变。所以我的代码如下:

应用程序.vue:

<template>
  <navbar></navbar>
  <component v-bind:is="currentView"></component>
</template>

<script>
 import Login from './components/Login'
 import Signup from './components/Signup'
 import Navbar from './components/Navbar'
 import NavbarInner from './components/NavbarInner'

 import store from './vuex/store'

 export default {
 name: 'app',
 data () {
   return {
     currentView: this.$store.state.currentView
   }
 },
 components: {
   Login,
   Signup,
   Navbar,
 },
 store
}
</script>

在 Navbar.vue 模板中,我保留了更改 currentView 状态的按钮和方法:

    <md-button class="navbar__link"
               @click="changeCurrentModal('Signup')">
      Sign Up
    </md-button>

    <md-button class="navbar__link"
               @click="changeCurrentModal('Login')">
      Login
    </md-button>

    export default {
     name: 'navbar',
     computed: {
       currentView () {
        return this.$store.state.currentView
      }
    },
    methods: {
      changeCurrentModal (curentView) {
        this.$store.commit('changeCurrentModal', curentView)
     }
   }
 }
 </script>

我的 store.js 文件如下所示:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
  currentView: 'Signup'
},
mutations: {
  changeCurrentModal: (state, currentView) => {
    console.log(currentView)
    state.currentView = currentView
  }
},
actions: {
   changeCurrentModal: ({commit}, currentView) => {
     commit('changeCurrentModal', currentView)
   }
  } 
})
4

2 回答 2

1

您应该做的是制作一个 getter 并使用计算属性将其拉入您的组件中。

你的 vuex 会变成...

...

export default new Vuex.Store({
   state: {
      currentView: 'Signup'
   },
   getters: {
      getCurrentView: state => {
          return state.currentView
      }
   }
   mutations: {
      ...
   },
   actions: {
      ...
   }
})

你的计算道具看起来像这样......

computed: {
  currentView () {
    return this.$store.getters.getCurrentView
  }
}

通过这样做,您将保持对 vuex 数据的反应性。

于 2016-11-23T16:08:53.850 回答
0

虽然你已经让 Vuex 工作了,但如果你还没有的话,你可能想看看 Vue-router。它会完成你想要的同样的事情,并且可能会提供更容易理解的代码。

于 2016-11-02T03:01:23.597 回答