本讲解基于Vue-cli(脚手架)搭建的项目。

Vuex 数据状态管理工具,整个流程类似依赖注入,相当于预先定义,倒推。(个人理解)

1. 安装vuex  命令行输入

  npm install vuex --save

2.在根目录的src下新建 store文件夹,并且在其内创建5个js文件。

Vuex非常适合新手的教程,保教不会!-LMLPHP

index.js中写入代码 (主要是汇集处理其他4个js文件)

import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as mutations from './mutations'
import * as getters from './getters'
import state from './rootState' Vue.use(Vuex) //引用vuex const store = new Vuex.Store({
state,
getters,
actions,
mutations
}) export default store;

在根目录的src下的 main.js 中引入store

import store from './store';   //引入store文件下的index.js和引入路由方式相同
并且在实例化 Vue对象时加入 store 对象:
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
配置完成后就可以使用了。
rootState.js   主要预先定义了一些将要处理的数据

actions.js    主要预先定义了一些方法,把从组件获取的数据提交到类似缓存状态
mutations.js  主要对rootState.js中的数据与缓存的数据进行赋值等操作
getters.js    主要获取了rootState.js中被处理的数据,等待被注入使用的组件中

新建一个test.vue
//引入vue,vuex,
<template>
<div>
<div class="content">
<h1>测试</h1>
<div>
<span>{{ msg }}</span>..
<!-- 注入的属性 -->
<button @click='fun'>获取数据</button>
          <!-- 注入的方法 -->
</div>
</div>
</div>
</template> <script>
import Vue from 'vue';
import { mapGetters, mapActions } from 'vuex'; // 这个例子的用意是:
// ①、用户点击button,触发绑定在click上的fun方法
// ②、fun是定义在actions.js中的,这个方法会调用vue自带的commit方法
// ③、commit方法会自动调用mutations中对应的方法
// ④、在mutations中更新store上的数据msg,从而Test.vue中的msg自动得到更新
export default {
name: 'test',
methods: {
...mapActions([ // 和引入的vuex中的mapActions对应
'fun', // 在src/store/actions.js中创建一个名为fun的方法 在这里注入即可使用(方法)
]),
},
computed: {
...mapGetters([ //和引入的vuex中的mapGetters对应
'msg' // 在src/store/getters.js中创建一个名为msg的方法 在这里注入使用 (计算属性)
]),
}
}
</script> <style scoped > </style>
再看 actions.js

//导出了fun这个方法 在test.vue中注入使用
//定义了个fun方法其中自带了第一个参数{{commit}},还可以在test.vue使用fun 这个方法时传入参数,即为这里的第二个参数,以此类推,这里没新传入参数
export const fun = ({commit})=>{
commit({
type: 'getMsg', // 这个type很重要,vue会自动去找mutations.js中名为getMsg的方法 //类似被注入的方法
msg:'提交的数据1111', // 这里的参数写死了,可以自定义,也可通过传参设定
});//commit方法作用类似把这其中的这个参数对象提交到缓存,以便在mutations.js中对这些数据处理
}

然后 mutations.js

//定义了个 getMsg 方法 传入两个参数 state(rootState.js中定义的数据),payload(actions.js中传来的对象)
export const getMsg = (state, payload) => {
state.msg = payload.msg;//赋值给想变化的值
}

之后 getters.js

导出msg这个计算属性 在test.vue中注入使用
export const msg = state => state.msg; //获取rootState.js的state作为参数(此时已经被mutations.js的方法赋值),再导出msg这个带值方法
最后基本过程:
用户点击button,触发绑定在click上的fun方法
fun是定义在actions.js中的,这个方法会调用vue自带的commit方法
commit方法会自动调用mutations中对应的方法
在mutations中更新store上的数据msg,从而Test.vue中的msg自动得到更新

本教程vue项目的完整地址在----------  https://github.com/TKBnice/vue-res

04-19 16:00
查看更多