美文网首页
单页面中使用多组件并使用vux通信

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

作者: 手指乐 | 来源:发表于2020-02-03 10:32 被阅读0次
    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的增减会同步到子组件

    相关文章

      网友评论

          本文标题:单页面中使用多组件并使用vux通信

          本文链接:https://www.haomeiwen.com/subject/xfxhxhtx.html