来分析下vuex的管理状态吧,若是你用过react中的redux的管理树,那我以为vuex对你来讲很容易掌握html
若是你仍是不太熟悉vuex是什么,那先看下官网https://vuex.vuejs.org/zh-cn/intro.html,vue
看下这张图:react
下面就举个例子会比较容易理解:ajax
就拿vue的分页组件来理解吧vuex
1. 建立 pagination.vue 文件。redux
<template> <div class="page-wrap"> <ul v-show="prePage" class="li-page" v-tap="{methods: goPrePage}">上一页</ul> <ul> <li v-for="i in showPageBtn" :class="{active: i === currentPage, pointer: i, hover: i && i !== currentPage}" v-tap="{methods: goPage, i: i}"> <a v-if="i" class="notPointer">{{i}}</a> <a v-else>···</a> </li> </ul> <ul v-show="nextPage" class="li-page" v-tap="{methods: goNextPage}">下一页</ul> </div> </template>
2.组件的做用域是独立的,父组件通讯经过 props 向其传递数据,分页组件经过 $emit 触发在父组件定义的事件实现和父组件的通讯,所以预设从父组件获取到需显示的总数 num 为 20 , limit 为 5,固然你也能够随意设置这两个值~函数
let that export default{ data(){ that = this return{ num: 20, limit: 5 } } }
3.计算几个变量,在这里可使用 vue 的计算属性 computedthis
// 总页数 totalPage 应该等于需显示的总数除以每页显示的个数,并向上取整,这个很好理解。 computed: { totalPage() { return Math.ceil(that.num / that.limit) } } // 偏移量 offset,由于点击上下页、制定页码均会改变 offset 变量,父组件也须要用到这个变量发送 ajax 请求,所以使用 vuex 存储 offset。 // pagination.vue computed: { offset() { return that.$store.state.offset } } // 当前页面 currentPage,当前页面是比较重要的一个变量,显示用户当前所处页数,已知偏移量和每页显示数量能够得出当前页面是两者的余数向上取整,由于页数不从0开始,所以 computed: { currentPage() { return Math.ceil(that.offset / that.limit) + 1 } } //跳转事件,分别点击上一页、下一页和指定页码
methods: {
goPage(params) { if (params.i === 0 || params.i === that.currentPage) return that.$store.commit('GO_PAGE', (params.i-1) * that.limit) that.$emit('getNew') }, goPrePage() { that.$store.commit('PRE_PAGE', that.limit) that.$emit('getNew') }, goNextPage() { that.$store.commit('NEXT_PAGE', that.limit) that.$emit('getNew') } }
4.vuex 部分spa
// vuex �store/index.js import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' Vue.use(Vuex); const state = { offset: 0 }; export default new Vuex.Store({ state, mutations })
// mutation-types.js export const PRE_PAGE = 'PRE_PAGE' export const NEXT_PAGE = 'NEXT_PAGE' export const GO_PAGE = 'GO_PAGE'
// mutation.js import * as types from './mutation-types' export default { // 分页 上一页 [types.PRE_PAGE] (state, offset) { state.offset -= offset }, // 分页 下一页 [types.NEXT_PAGE] (state, offset) { state.offset += offset }, // 分页 跳转到指定页码 [types.GO_PAGE] (state, offset) { state.offset = offset } };
最后你想要监听store里的state的变化你能够用这个2个函数,在页面里 用computed和watch来设计
computed: { initMovies() { return this.$store.state.movies; }, }, watch: { initMovies(val) { this.movies = val; } },
对了 你也能够用this.$store.dispatch来触发actions里面type,最后在mutation.js里改变state。
对于复杂的项目来讲,用vuex来管理,是最好的选择。