Using vuex to transfer parameters between components

Take a vue Learning Note (First Blog)

Objective:
By collapsed parameter control, ant-design layout menu is retrieved and opened
Question:
After splitting the layout into several components, the parameters passed between components, trying to use $emit and props, felt unsatisfactory.
After checking a lot of information, I finally decided to use vuex.

  • Create a store directory in the project

  • index.tx content:
import Vue from 'vue'
import Vuex from 'vuex'
import layout from "@/store/modules/layout/layout";


Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

const store = new Vuex.Store({
        modules: {
            layout
        },
        strict: debug

    })
export default store

Content of layout

const state = {
    collapsed: false
}

const actions = {
    setCollapsed(context:any,value:boolean){
        context.commit('setCollapsed',value)
    }
}

const mutations = {
    setCollapsed(state: any, value: boolean) {
        state.collapsed = value
    }
}
const getters = {
    getCollapsed(state:any){
       return  state.collapsed
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}

Content of Component A (only js code is written)

<script>
    export default {
        name: "Header",
        computed:{
            collapsed:{
                get(){
                    return this.$store.getters.getCollapsed
                },
                set(){
                    this.$store.dispatch('setCollapsed',!this.collapsed)
                }
            },
        },
    }
</script>

Content of Component B (only js code is written)

<script>

    export default {
        name: "Sider",
        computed:{
            collapsed:{
                get(){
                    return this.$store.getters.getCollapsed
                },
                set(){
                    this.$store.dispatch('setCollapsed',!this.collapsed)
                }
            }
        },
    }
</script>

Experience:
I write back-end, just learn vue, there is no front-end basis (if jq counts when I did not say), feel that this Vue is quite magical.

Tags: Vue

Posted on Tue, 08 Oct 2019 12:42:06 -0700 by dbo