一、vuex
vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
一个全局的状态管理器
初步了解vuex里面各个状态的功能:
import { createStore } from 'vuex'
export default createStore({
// 全局状态初始值
state: {
},
//计算state, 获取对应的值
getters: {
},
//更新状态的方法-更新state的唯一方法 , commmit mutations
mutations: {
},
//可以异步操作,可以返回promise,更改数据还是传递到mutations去更改
actions: {
},
//数据比较多的时候,分模块
modules: {
}
})
1、更改state初始状态有两种方法(mutations/actions)
【1】在mutations里面更改
// store/index.js
//更新状态的方法-更新state的唯一方法 , commmit mutations
mutations: {
setCount(state, num) {
state.count = num
}
}
//views/pages/Login
//[1]引入store
import { useStore } from 'vuex'
const store = useStore()
const count = store.state.count
const handleLogin=()=>{
store.commit('setCount', 100) //使用commit
console.log(store.state.count)
}
【2】在actions里面更改(本质还是传入mutations中进行更改)异步函数
// store/index.js
//更新状态的方法-更新state的唯一方法 , commmit mutations
mutations: {
setCount(state, num) {
state.count = num
}
}
//views/pages/Login
//[1]引入store
import { useStore } from 'vuex'
const store = useStore()
const count = store.state.count
const handleLogin=()=>{
store.commit('setCount', 100) //使用commit
console.log(store.state.count)
}
2、getters
//计算state, 获取对应的值
getters: {
countState(state){
return state.count>=1 //返回true 或者false
}
}
//getter
console.log('getters改变前',store.getters.countState)
const handleLogin=()=>{
store.dispatch('setCountPromise',-101).then(res=>{
alert('num不大于100')
console.log('getters改变后',store.getters.countState)
}).catch(err=>{
alert(err)
})
}
3、modules
模块化
//在index里引入number.js userinfo.js
import number from './state/number.js'
import userinfo from './state/userinfo.js'
export default createStore({
//数据比较多的时候,分模块
modules: {
number,
userinfo
}
})
//在登录页面 都多加一层number
<script>
import { reactive, toRefs} from 'vue'
import { useStore } from 'vuex'
export default {
name:'Login',
setup(){
const store = useStore()
const count = store.state.number.count
const data= reactive({
loginData: {
name:'',
password:''
}
})
//mutations
const handleLogin=()=>{
store.commit('number/setCount', 100)
console.log(store.state.number.count)
}
//actions
const handleLogin=()=>{
store.dispatch('number/setCountPromise',101).then(res=>{
alert('num不大于100')
}).catch(err=>{
alert(err)
})
}
//getter
console.log('getters改变前',store.getters["number/countState"])
const handleLogin=()=>{
store.dispatch('setCountPromise',-101).then(res=>{
alert('num不大于100')
console.log('getters改变后',store.getters["number/countState"])
}).catch(err=>{
alert(err)
})
}
return{
...toRefs(data),
handleLogin
}
}
}