什么是vuex?
1.就是vue保存数据的地方。
2.刷新就丢失。
3.具有双向数据绑定的特点。
为什么要vuex?
1.保存全局变量,且更好的监控。
2.有的组件传值相当复杂,就可以放在vuex。
3.登录后的用户信息等复用性高,且多处使用的数据放在vuex。
安装vuex
命令: npm install vuex --save
main.js
import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
vuex里面有什么?
原文连接:https://blog.csdn.net/zzh990822/article/details/109573791
以下是基本内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//数据
const state={
count:10
}
//action 执行异步操作,不可以修改state数据
const actions={
getParamSync (context,Object) {
//处理异步操作
setTimeout(()=>{
//3.通过commit提交一个名为getParam的mutation
//action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation
context.commit('increment',Object)
},3000)
}
}
//mutation 可直接修改state数据
const mutations={
increment(state,value){
state.count += value;
},
decrement(state,value){
state.count -=value;
}
}
//getter
const getters = {
newCount:state => state.count * 3
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
如何使用vuex
更改state数据时用 this.$store.commit(“increment”, 1); //函数名,传参
this.$store.state.dataname 负责展示数据,也可以直接赋值,但是不推荐
vuex的持久化
注意事项 只有这样更改数据this.$store.commit(“increment”, 1);才能持久化,this.$store.state.dataname=value 这样不行。
使用vuex-persistedstate包
命令框里输入
mpn i vuex-persistedstate --save
然后上代码
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
const state = {
user:'',
}
export default new Vuex.Store({
state,
mutations: {
setState(state,opt){
for(let [key,val] of Object.entries(opt)){
state[key] = val;
}
}
},
plugins: [
createPersistedState({
storage: window.sessionStorage,
key: "user",
reducer(state){
return{
user:state.user
}
}
})
]
});