Vuex 核心功能与组件通信
-
简单计数器案例:
html
<!-- App.vue --> <template> <div> <h2>当前数值:{{ $store.state.num }}</h2> <button @click="increment">+1</button> </div> </template> <script> export default { methods: { increment() { this.$store.commit('INCREMENT') } } } </script>
-
Store 配置:
javascript
// store/index.js export default new Vuex.Store({ state: { num: 0 }, mutations: { INCREMENT(state) { state.num++ } } })
-
多组件数据共享:
javascript
// Store配置 state: { studentList: [] }, mutations: { ADD_STUDENT(state, student) { state.studentList.unshift(student) } } // 组件调用 this.$store.commit('ADD_STUDENT', { id: Date.now(), name: this.name })