小生愛




   
        <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++
                    }
                }

                // 创建store
                const store = new Vuex.Store({
                    state,
                    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 () {
                        // commit(变更事件名, 参数)
                        this.$store.commit('increment', {
                            name: '小花',
                            age: 27
                        })
                    }
                }
            }
        </script>