1、配置
src\store\index.js配置文件
import { createStore } from 'vuex'
export default createStore({
// 设置全局数据
state: {
count: 0,
list: []
},
// 计算属性
getters: {
totalPrice (state) {
return state.count * 100
}
},
// 修改状态方法(同步)
mutations: {
// 无传参
setCount (state) {
state.count++
},
// 有传参,num为传入参数
setCountNum (state, num) {
state.count += num
},
setList (state, arr) {
state.list = arr
}
},
// 修改状态方法(异步)
actions: {
getList (context) {
fetch('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=2').then(res => res.json()).then(result => {
console.log(result, '接口返回数据');
context.commit('setList', result)
})
}
},
modules: {
}
})
2、引入
main.js文件
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
3、使用
<template>
<h1>数量-映射前:{{$store.state.count}}</h1>
<h1>数量-映射后:{{count}}</h1>
<h1>数量-映射后:{{maxCount}}</h1>
<h1>总价-映射前:{{$store.getters.totalPrice}}</h1>
<h1>总价-映射后:{{totalPrice}}</h1>
<button @click="change">修改数量-映射前</button>
<button @click="setCountNum(2)">修改数量-映射后</button>
</template>
<script>
import {mapState,mapMutations,mapActions,mapGetters} from 'vuex'
export default {
computed:{
// 映射后
...mapState(['count']),
// 映射后
// 自定义变量名
...mapState({
maxCount:(state)=>state.count
}),
// 映射后
...mapGetters(['totalPrice'])
},
methods: {
// 映射后
...mapMutations(['setCountNum']),
// 映射后
...mapActions(['getList']),
// 映射前
change () {
this.$store.commit('setCountNum', 10)
}
},
mounted () {
// 映射前
// this.$store.dispatch('getList')
// 映射后
this.getList()
}
}
</script>