首先先正经的来一段官网的"忠告":
vuex需要遵守的规则:
一、应用层级的状态应该集中到单个 store 对象中。
二、提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
三、异步逻辑都应该封装到 action 里面。
文件目录结构
文件之间的关系:
store文件夹 - 存放vuex的系列文件
store.js - 引入vuex,设置state状态数据,引入getter、mutation和action
getter.js - 获取store内的状态
mutation.js - 更改store中状态用的函数的存储之地
action.js - 提交mutation以达到委婉地修改state状态,可异步操作
简单而又普通的写法
store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const state = {
a: '初始值',
b: 'balabala...'
}
export default new Vuex.Store({
state,
actions,
mutations
})
main.js文件中(从根组件注入store,就像注入router一样):
通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
import store from './store/index'
new Vue({
el: '#app',
router,
store,
...
})
Getter.js 的简单配置( store 的计算属性,接受state为参数)
export default {
doneTodos: state = >{
return state.todos.filter(todo = >todo.done)
}
}
获取(某组件的计算属性内部):
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
可传参的getter属性的简单配置
export default{
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
获取(某组件的计算属性内部):
computed: {
getTodoById() {
return this.$store.getters.getTodoById(‘参数’)
}
}
mutation.js简单配置:
export default {
increment(state) {
//变更状态
state.count++
}
}
触发(组件中)
this.$store.commit(state,payload)
actions.js简单配置:
export default{
action (context) {
//异步操作
setTimeout(()=>{
//变更状态
context.commit('mutationFunName',value)
})
}
}
触发(组件的)
this.$store.dispatch('mutationFunctionName')
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有