我使用VueJs VueX构建SPA,我在一个组件中单击按钮"Login"和"Sign Up",在其他组件中单击 <component></component>
标签,其中有条件地渲染1到模态("SignUp"表单和"Login form") . 模态也是组件 .
当我调用console.log时,我看到state.currentView根据点击的按钮而改变,但是检查{{$ data | json}}里面的标记显示状态不是't changed and what is more important the modal are not changing. So I' ve代码如下:
App.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)
}
}
})
2 回答
虽然您可以使用Vuex,但如果您还没有,可能需要查看Vue-router . 它将完成您想要的相同的事情,并可能提供更容易遵循的代码 .
你应该做的是使用计算属性制作一个getter并将其拉入你的组件 .
你的vuex会变成......
你计算出的道具看起来像这样......
通过这样做,您将保持与vuex数据的反应性 .