Vuex:状态管理模式,它采用集中式存储管理应用的所有组件的状态,应用于多级或者多个界面共享,如 登录状态,用户名,头像,地理位置,收藏,购物车等
项目结构
1> 应用层级的状态应该集中到单个 store 对象中。
2> 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
3> 异步逻辑都应该封装到 action 里面。
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
安装:
npm install vuex --save
一、搭建Vuex框架
1、安装插件
Vue.use(Vuex)
2、创建对象
const store = new Vuex.Store({
state:{
},
mutations:{
},
action:{
},
getters:{
}
})
3、导出
export default store
4、再main.js中导入挂载
import Store from './store'
import store from "./store";
......
Vue.prototype.$store = store
new Vue({
render: h => h(App),
Store,
}).$mount('#app')
二、其他参数
1、State:State单一状态树,Vuex的store中的state是响应式的,当state中的数据发生改变时,Vue组件会自动更新,其规则:(1)提前在
2、Getter
3、Mutation:传递参数(n个参数/对象),参数为Mutation的载荷,用于修改,其中方法必须为同步方法
4、Action
5、Module