小生愛

        


        <script>
                import Vue from 'vue'
                import Vuex from 'vuex'

                // 告诉 vue 使用 vuex
                Vue.use(Vuex)

                // 创建一个对象保存初始状态
                let state = {
                    count: 0
                }

                let mutations = {
                    // arg 是接受的第二个参数
                    increment (state, arg) {
                        // 变更状态
                        state.count++
                    }
                }

                // actions 中可以执行任何异步操作
                // 不能在mutations中进行异步操作
                // 因为多个地方同事改变state 不知道是谁改变的 不好跟踪
                let actions = {
                    // {commit} 解构赋值
                    // arg 接收其他参数
                    increment ({commit}, arg) {
                        // context context具有和Store实例相同方法和属性
                        // 如果定义了Modules context就是当前模块的store属性 包含mutations state getters
                        commit('increment')
                    }
                }

                // 创建store
                const store = new Vuex.Store({
                    state,
                    actions,
                    mutations
                })

                export {store}
        </script>
        

        

        <!-- teacher.vue -->

        <template>
            <div>
                <Search></Search>
            </div>
        </template>

        <script>
            import {store} from './store.js'
            import Search from './search.vue'

            export default {
                // store 提供给 store 选项 可以把store的实例注入到所有的子组件
                store,
                components: {
                    Search
                }
            }
        </script>




        <!-- search.vue -->

        <template>
            <div class="search">
                <p>{{name}}</p>
                <button @click="increment">+</button>
            </div>
        </template>

        <script>
        export default {
            computed: {
                name () {
                    // this.$store.state.count 获取store中的状态
                    return this.$store.state.count
                }
            },
            methods: {
                increment () {
                    // this.$store.dispatch 分发Action
                    // 可以添加额外参数
                    this.$store.dispatch('increment', '小花')
                }
            }
        }
        </script>