1 简介
vue的状态(数据)管理工具,多组件共享数据(组件之间不需要有什么关系),它相当于一个中间对象,所有的东西都是它自己的,我们页面只需要使用就可以了。
2安装
安装 cnpm i vuex@3 --save
3使用核心
1在src下新建一个文件夹store 下新建个文件 index.js
举个小例子
1
src/store/index.js.
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
2 在main.js里面挂载
举个小例子
2 main.js
import store from "./store"
new Vue({
store,
router,
})
vuex的使用核心
const store = new Vuex.Store({
state, // 状态
mutations //修改状态的方法
getters // state它的计算属性。 computed
actions. // 可以提供上下文环 (异步修改state)
});
export default store;
1state的用法是用来存储数据各个页面都可以调用
const state = {
count:10,
user:{}
}
this.$store.state[属性]
// 帮助我们封装了一个对象 ...拓展出来就是原生的写法
//这个是辅助函数
import {mapState} from "vuex"
//辅助函数要在计算属性里面使用 名字要和 state 存数据的名字一样
computed:{
...mapState(['count','user'])
//数组里的属性一定要与 state里面属性一样,否则获取不到
2mutations 是用来修改 state 数据的方法
mutations唯一指定能修改state 如果想修改state 必须只能使用mutations的方法
const mutations = {
// state 第一个参数
// payload 页面传递参数s
ADD_COUNT(state,payload){
// 执行逻辑
}
}
//在页面调用这个叁数
this.$store.commit("ADD_COUNT",参数)
import {mapMutations} from "vuex"
methods:{
...mapMutations(["ADD_COUNT"])
}
3getters 它是state的计算属性
state它的计算属性,state的数据改变改的时候自动执行,跟computed使用方法一摸一样
const getters ={
todos_start(){
return. 必须return
}
}
//
this.$store.getters.todos_start
import {mapGetters} from "vuex"
computed:{
...mapGetters(['todos_start',....])
}
4actions 它是用来请求数据
可以提供上下文环境,让commit()提交的可能性更多, (发送ajax 执行异步) , 获取到回调到结果,然后提交commit 修改state
const actions = {
login(context){
context 获取其它模块的数据 需要使用 context.rootState .rootGetters
context 是 store 镜像
// 发送登陆请求。--
// 看返回结果 , 如果对。 commit('SET_USER',payload) 修改state
// 否则 请求失败 提示失败
}
}
this.$store.dispatch('login',参数)
import {mapActions} from "vuex"
methods:{
...mapActions(["login"])
}
5plugins vuex数据本地存储
vuex的缺点是什么? 刷新的时候数据不保留?
安装 npm i vuex-persistedstate --save.
plugins: [
Per({
storage: window.sessionStorage, //修改存储方法
key: "sy2201", // 默认key vuex
paths: ["user"], //默认都存储 设置存储那些属性
}),
],
总结vuex
vuex它是vue的状态管理工具,适用多组件之间共享数据,它有自己的一些属性,作用各不相同
state 存储状态
mutations 修改状态
getters state的计算属性
actions 给修改state提供异步环境,我们一般在这里面可以发送请求
modules 它将数据进行模块 ,后期好维护
plugins 持久化存储