state、getters、mutations、actions、modules五大类
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、使用
state用法
demo1.vue文件
<template>
<h1>数量:{{$store.state.count}}</h1>
</template>
mutations用法(无传参、有传参)
demo2.vue文件
<template>
<h1>数量:{{$store.state.count}}</h1>
<button @click="change">修改数量</button>
</template>
<script>
export default {
methods: {
change () {
// 方法一:无传参
// this.$store.commit('setCount')
// 方法二:有传参,传参为10
this.$store.commit('setCountNum', 10)
}
}
}
</script>
actions用法
demo3.vue文件
<script>
export default {
methods: {
},
mounted () {
this.$store.dispatch('getList')
console.log(this.$store.state.list,'接口返回数据');
}
}
</script>
getters用法
demo4.vue文件
<template>
<h1>总价:{{$store.getters.totalPrice}}</h1>
<button @click="change">修改数量</button>
</template>
<script>
export default {
methods: {
change () {
// 方法一:无传参
// this.$store.commit('setCount')
// 方法二:有传参,传参为10
this.$store.commit('setCountNum', 10)
}
}
}
</script>