单页面中使用多组件并使用vux通信

  1. './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
  1. '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>
  1. 路由中配置嵌套子组件
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中

  1. 子组件 'Test'
<template>
  <div>
    <div>test:{{this.$store.state.count}}</div>
    <div>test:{{this.$store.getters.getCount}}</div>
  </div>
</template>

5.在父组件中显示子组件,父组件对vuex中count的增减会同步到子组件

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容