cnpm i vuex axios -S 1 建立Vuex 仓库 import Vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new VueX.store({ state: {//存放状态}, mutations:{//惟一修改状态的地方,不在这里作逻辑处理} }) export default store 2 在入口文件main.js下引入store import store from './store/index.js' 将store 放到根实例里 以供全局使用 new Vue({ el:'#app', store, components:{App}, template:<App/> }) 开始使用store(以home组件为例)
Vuex的使用也是一种渐进式的,你能够从最简单的开始使用,根据经验和技术的增长,再渐进加强对它的使用,若是按照级别算vuex的使用能够从最基本的t1级别开始,先总结最基本的前三个版本,后续有时间再总结其余的。vue
1. 在hoome/script.js中进行请求数据 import Vue from 'vue' import axios from 'axios' export default { mounted(){ axios.get('请求数据的接口') .then((res)=>{this.$store.commit('changeList',res.data)}) //changeList至关于调用了在store.mutations中定义的修改状态的方法 //res.data 就是在改变状态时要修改的数据,须要在这传递过去。 .catch((err)=>{console,log(err)}) } } 2. 在store/index.js中定义 import Vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new VueX.store({ state: { //存放状态 list: [ ] //存放一个空的数组 }, mutations:{ //惟一修改状态的地方,不在这里作逻辑处理 //定义一个修改list的方法 //state 指上面存放list的对象,data 为在请求数据出传过来请求到的数据 changeList (state,data) { state.list = data //将请求来的数据赋值给list } } }) export default store 3. 在home/index.vue中渲染 <template> //渲染数据的时候经过this.store.state.list直接从store中取数据 //还能够从其余组件经过这种方法去用这个数据无需从新获取 <li v-for='item of this.store.state.list' :key='item.id'>{{item.name}}</li> </template> 注意点: ( 若是咱们在home组件中获取的数据,能够在其余组件中使用,可是是当页面刷新默认进入home页,也就是至关于修改了数据,再点击其余页面也能有数据。若是咱们在user组件中获取的数据要在home组件中使用,当页面刷新数据是不会显示的,由于此时尚未触发user组件中的更改数据的方法,因此数据为空,当点击user页面时,就会有数据,这个时候再去点击home页面咱们就可以看到在home 组件中使用user组件中获取的数据了。解决这种问题的办法能够将数据存到本地一份或者都在首页进行请求数据 )
在页面进行渲染的时候咱们须要经过this.store.state去拿数据,这样的写法太长并且不太好 用计算属性结合mapState去解决这个问题 1 在home/script.js中进行操做 import Vue from 'vue' import mapState from 'vuex' import axios from 'axios' export default { computed:{ //mapState为辅助函数 ...mapState(['list']) }, mounted(){ axios.get('请求数据的接口') .then((res)=>{this.$store.commit('changeList',res.data)}) .catch((err)=>{console,log(err)}) } } 2 在home/index.vue中渲染 <template> <li v-for='item of list' :key='item.id'>{{item.name}}</li> </template>
使用常量去代替事件类型(便于查看状态,利于维护) 1 在store下建立mutation-type.js export const CHANGE_LIST = 'CHANGE_LIST' 2 在store/index.js引入mutation-type.js import Vue from 'vue' import Vuex from 'vuex' import {CHANGE_LIST } from‘./mutation-type.js’ vue.use(Vuex) const store = new VueX.store({ state: { list: [ ] //存放一个空的数组 }, mutations:{ //咱们可使用Es6风格的计算属性命名功能来使用一个常量做为函数名 [CHANGE_LIST] (state,data) { state.list = data //将请求来的数据赋值给list } } }) export default store 3 在home/script.js中进行引入 import Vue from 'vue' import mapState from 'vuex' import axios from 'axios' import {CHANGE_LIST} from ‘../../store/mutation-type.js’ export default { computed:{ //mapState为辅助函数 ...mapState(['list']) }, mounted(){ axios.get('请求数据的接口') .then((res)=>{this.$store.commit(CHANGE_LIST,res.data)}) .catch((err)=>{console,log(err)}) } }