目录
解决冲突的方法:给某个状态机中变量重命名,用辅助函数mapState()。
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
Vuex是一个状态管理模式,状态机,将组件共享的数据放到状态机中统一管理,组件想拿数据可以从自己的数据模型中拿,也可以从仓库中拿,把vuex理解成一个仓库。
把A组件和B组件的数据放到Vuex中,A组件想要获取B组件数据从vuex中拿,B组件想要获取A组件的数据从Vuex拿。
使用
1、生成仓库/状态机配置对象---五个属性可选
2、生成Vuex Store构造函数的状态机---new Vuex.Store
3、注册状态机---router
4、访问状态机中的数据---$store.state.xx或鼠标触发提交突变、分发动作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入vue,引入vuex -->
<script src="./js/vue-2.6.12.js"></script>
<script src="./js/vuex-3.5.1.js"></script>
</head>
<body>
<div id="app">
<!-- 4、访问状态机中的数据 -->
{
{$store.state.storeMsg}}
-------------------------------
{
{$store.getters.storeMsgUpper}}
<button @click="$store.commit('changeMsg','数据修改为test')">提交突变</button>
<button @click="$store.dispatch('getMsg','terry')">分发动作</button>
</div>
<script>
// 1、生成仓库/状态机配置对象
let storeCnf = {
// 类似于组件内的data(){},在state中存放的是组件之间的共享数据
state: {
storeMsg: '状态机中的数据hello'
},
// 类似于computed属性,对state中的属性处理之后再返回,从state中派生出来的
getters: {
// 默认参数为state
storeMsgUpper(state) {
return state.storeMsg.toUpperCase()
}
},
// 突变,同步操作,唯一修改state中数据的方式
mutations: {
// 参数为state、payload,state为默认参数类似于事件中的event,payload载荷形参
changeMsg(state, payload) {
state.storeMsg = payload
}
},
// 动作,存放的是异步请求
actions: {
// 参数为sto、payload,sto是类状态机对象,payload载荷形参
// getMsg(sto, payload) {
// 将sto解构出来为{commit,dispatch,state,getters}
getMsg({commit,dispatch,state,getters}, payload) {
// console.log(sto);
// 提交突变
// sto.commit('突变事件名称','传递的数据res');
// sto.commit('changeMsg',payload);
// sto解构出来提交突变
commit('changeMsg', payload);
// 分发动作
// s