- './store/index.js'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
},
getters: {
getCount: function(state) {
return state.count + 1
}
},
mutations: {
add(state) {
state.count = state.count + 1
},
reduce(state) {
state.count = state.count - 1
}
},
actions: {
addAction({ commit }) {
commit('add');
}
}
})
export default store
- 'HelloWord'組件:
<template>
<div class="hello">
<div>{{this.$store.state.count}}</div>
<div>{{this.$store.getters.getCount}}</div>
<button @click="add">加</button>
<button @click="reduce">減</button>
<br />
<router-link to="/Test">顯示子組件</router-link>
<router-view></router-view>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
methods: {
...mapActions(["addAction"]),
add() {
this.addAction();
},
reduce() {
this.$store.commit("reduce");
}
}
};
</script>
<style scoped>
h1,
h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
- 路由中配置嵌套子組件
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Test from '@/components/Test'
Vue.use(Router)
export default new Router({
routes: [{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
children: [{
path: '/Test',
name: 'Test',
component: Test
}]
}
// {
// }
]
})
路由要配置嵌套子組件,如果直接配置
path: '/Test',
name: 'Test',
component: Test,
會渲染到App.vue中的的最外層組件中,不會渲染到HelloWorld的router-view中
- 子組件 'Test'
<template>
<div>
<div>test:{{this.$store.state.count}}</div>
<div>test:{{this.$store.getters.getCount}}</div>
</div>
</template>
5.在父組件中顯示子組件拥坛,父組件對vuex中count的增減會同步到子組件