vuex简单使用
1、创建src/store/index.js----仓库所在地----暴露store
2、main.js入口文件处引入store,挂载到Vue根实例中
3、创建store/movie.js-----电影页面对应的状态管理模块
export default {
state: {
},
getters: {
},
actions: {
},
mutations: {
}
}
4、定义电影页面关联的初始状态
export default {
state: {
movielist: []
},
getters: {
},
actions: {
},
mutations: {
}
}
5、定义异步操作action和改变状态mutation
export default {
state: {
movielist: []
},
getters: {
},
actions: {
getMovielist ({commit}) {
}
},
mutations: {
changeMovielist (state, data) {
state.movielist = data
}
}
}
6、实现异步操作中的数据请求-----src/api/movie.js
import axios from 'axios'
export default {
getMovielist (cb) {
axios.get('http://localhost:3000/api/movies')
// .then(({data}) => {cb(data)})
.then((res) => {cb(res.data)})
.catch((err) => {console.log(err)})
}
}
7、实现store/movie.js中的action的后续操作-----提交mutation改变数据源
import movieapi from '@/api/movie.js'
export default {
state: {
movielist: []
},
getters: {
},
actions: {
// getMovielist ({commit}) {
// movieapi.getMovielist((data) => {commit('changeMovielist', data)})
// },
getMovielist (context) {
movieapi.getMovielist((data) => {context.commit('changeMovielist', data)})
}
},
mutations: {
changeMovielist (state, data) {
state.movielist = data
}
}
}
8、组件movie组件的js中,添加一个选项computed,用来接收store中的数据----使用mapState辅助函数
import {mapState} from 'vuex'
export default {
computed: { //你store/movie中定义的初始状态是什么,key值就是什么,中间{}中的store/index.js中的modules中的key值
...mapState({
movielist: ({movie}) => movie.movielist
})
}
}
9、提交action---组件mounted函数中
import {mapState} from 'vuex'
export default {
computed: { //你store/movie中定义的初始状态是什么,key值就是什么,中间{}中的store/index.js中的modules中的key值
...mapState({
movielist: ({movie}) => movie.movielist
})
},
mounted () {
this.$store.dispatch('getMovielist')
}
}
10、组件的模板中可以直接使用movielist渲染数据
<ul>
<li v-for='item in movielist' :key='item.id'>
{{item.title}}
</li>
</ul>
11、分页功能
casts组件中添加了一个按钮,模拟下一页
<button @click="getData()">下一页</button>
在其js中添加
methods: {
getData () { //下一页
this.$store.dispatch('getCastsPagingList',{skipNum:2,limitNum:5})
}
},
store/casts.js
actions: {
getCastsList (context) {
castsapi.getCastsList((data) => {context.commit('changeCastslist', data)})
},
getCastsPagingList (context, option){
castsapi.getCastsPagingList(option, (data) => {context.commit('changeCastsPagingList', data)})
}
},
mutations: {
changeCastslist (state, data) {
state.castslist = data
},
changeCastsPagingList (state, data) {
state.castslist = [...state.castslist, ...data]
}
}
}
api/casts.js
import axios from 'axios'
export default {
getCastsList (cb) {
.then(({data}) => {cb(data)})
.catch((err) => {console.log(err)})
},
getCastsPagingList ({limitNum, skipNum}, cb) {
console.log(limitNum)
console.log(skipNum)
axios.get('http://localhost:3000/api/castspaging?limitNum='+ limitNum+'&skipNum='+skipNum)
.then(({data}) => {cb(data)})
.catch((err) => {console.log(err)})
}
}