vuex相关

vuex是一个状态管理模式,且是响应式的
下载vuexnpm install vuex --save
注意版本问题:vue 的 2.x 版本对应 vuex 的 3.x 版本,vue 的 3.x 版本对应 vuex 的 4.x 版本

  1. 下载之后需要在src文件夹下新建store文件夹(store为仓库意思,存储所有状态)
  2. 创建index.js文件,引入并安装,创建及导出
//首先导入
import Vue from "vue";
import Vuex from "vuex";
//使用
Vue.use(Vuex);
//创建
const store = new Vuex.Store({
  state() {
    return {
      count: 0
    };
  },
  mutations: {
    
  },
  actions: {},
  getters: {},
  modules: {}
});
//导出
export default store;
  1. 需在main.js中导入,挂载到vue上
import Vue from "vue";
import App from "./App";
import store from "./store";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  store,
  render: h => h(App)
});

使用

  1. 需要在浏览器安装devtools,用于调试
  2. store下面index.js页面中
    state存放的是需要共享的状态在页面使用vuex中存储的状态为
    $store.state.counter
  3. 页面中需要对state中存放的状态进行修改时
    需要先在store中mutations中定义方法,在页面中调用
    使用$store.commit() 括号中传入store里定义的方法名
    在这里插入图片描述

在这里插入图片描述

核心概念

State

  1. 存储共享状态
  2. 单一状态树(单一数据源,只使用一个store)

Getters

类似于组件中计算属性,在数据展示前进行处理

 getters: {
    //可以传两个参数state,getters
    moreExp(state) {
      return state.movies.filter(movies => movies.price > 35);
    },
    moreExpLength(state, getters) {
      return getters.moreExp.length;
    },
    morePrice(state) {
    //可以return一个function
      return function(price) {
        return state.movies.filter(movies => movies.price > price);
      };
    }
  },

页面中使用getters

    <h2>{{ $store.state.movies }}</h2>
    <h2>{{ $store.getters.moreExp }}</h2>
    <h2>{{ $store.getters.moreExpLength }}</h2>
    <h2>{{ $store.getters.morePrice(40) }}</h2>

需要在页面进行传参操作时,可以在getters中return一个function用于接收参数

 morePrice(state) {
    //可以return一个function
      return function(price) {
        return state.movies.filter(movies => movies.price > price);
      };
    }
 <h2>{{ $store.getters.morePrice(40) }}</h2>

Mutation

vuex中store状态更新的唯一方式就是通过提交mutation
同步操作
可以在commit提交时,在后面跟上参数
在index.js中定义mutations

mutations: {
    // 方法
    addCount(state, count) {
      state.count += count;
    },
    addMovies(state, con) {
      state.movies.push(con);
    }
  },

在页面中通过commit提交

	<button @click="addCount(5)">+5</button>
    <button @click="addMovies">添加</button>
  methods: {
    addCount(count) {
      this.$store.commit("addCount", count);
    },
    addMovies() {
      const movies = { id: 5, name: "xiaoliyu", price: 38 };
      this.$store.commit("addMovies", movies);
    }
  }

参数可以是对象

在index.js中

mutations: {
	 //payload 负载
    addCount(state, payload) {
      state.count += payload.count;
    }
  },

在页面中提交时使用type

 addCount(count) {
      // this.$store.commit("addCount", count);
      this.$store.commit({
        type: "addCount",
        count
      });

Action

异步操作
在mutations中可以使用异步操作,但是此操作不能被devtools监听,所以进行异步操作还是要在action中进行,对数据进行函数处理还是在mutations中进行

  mutations: {
      upda(state, payload) {
      state.info.name = payload;
    }
},
  actions: {
    // 异步操作
    aup(context,payload) {
      // context  上下文  默认属性
      setTimeout(() => {
        context.commit('upda',payload)
      },1000);
    }
  },

页面通过dispatch使用

    upda() {
      this.$store.dispatch('aup', "zzzy");
    }

dispatch可以传递更多信息

 mutations: {
      upda(state) {
      state.info.name = "zzzy";
    }
},
  actions: {
    // 异步操作
    aup(context,payload) {
	// context  上下文
       setTimeout(() => {
         context.commit("upda"), console.log(payload.message), payload.success();
      }, 1000);
    }
  },
    upda() {
      this.$store
        .dispatch("aup", {
         message: "携带信息",
         success() {
            console.log("成功");
           }
        })
    }

在这里插入图片描述

配合promise使用

  actions: {
    // 异步操作
    aup(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit("upda");
          console.log(payload.message);
          resolve("1111");
        }, 1000);
      });
    }
  },
    upda() {
      this.$store
        .dispatch("aup", {
          message: "携带信息"
        })
        .then(res => {
          console.log("成功");
          console.log(res);
        });
    }

在这里插入图片描述

Module

划分模块

const moduleA = {
  state: {
    name: "海贼王"
  },
  getters: {
    fullName(state) {
      return state.name + "123";
    },
    fullName2(state, getters) {
      return state.name + getters.fullName + "456";
    },
    fullName3(state, getters, rootGetters) {
      return state.name + getters.fullName2 + rootGetters.count;
    }
  },
  mutations: {
    updateName(state, payload) {
      state.name = payload;
    }
  },
  actions: {
    changeName(context, payload) {
      setTimeout(() => {
        // 可以拿到根状态下的getters
        console.log(context.rootGetters.moreExp); 
        context.commit("updateName", payload);
        console.log(context);
      });
    }
    // 对象解构写法
    // changeName({ state, commit, rootState }, payload) {
    //   setTimeout(() => {
    //     commit("updateName", payload);
    //     console.log(state);
    //     console.log(rootState);
    //   });
    // }
  }
};
const store = new Vuex.Store({
  state() {
    return {
      count: 0,
      movies: [
        { id: 1, name: "海贼王", price: 20 },
        { id: 2, name: "加勒比海盗", price: 30 },
        { id: 3, name: "泰坦尼克号", price: 40 },
        { id: 4, name: "诺曼底登陆", price: 50 }
      ],
      info: {
        name: "cala",
        age: 28,
        height: 178
      }
    };
  },
  mutations: {
    // 方法
    // 默认参数state
    add(state) {
      state.count++;
    },
    sub(state) {
      state.count--;
    },
    // addCount(state, count) {
    //   state.count += count;
    // },
    addCount(state, payload) {
      state.count += payload.count;
    },
    addMovies(state, con) {
      state.movies.push(con);
    },
    upda(state) {
      state.info.name = "zzzy";
    }
  },
  actions: {
    // 异步操作
    aup(context, payload) {
      // context  上下文
      // setTimeout(() => {
      //   context.commit("upda"), console.log(payload.message), payload.success();
      // }, 1000);
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit("upda");
          console.log(payload.message);
          resolve("1111");
        }, 1000);
      });
    }
  },
  getters: {
    moreExp(state) {
      return state.movies.filter(movies => movies.price > 35);
    },
    moreExpLength(state, getters) {
      return getters.moreExp.length;
    },
    morePrice(state) {
      return function(price) {
        return state.movies.filter(movies => movies.price > price);
      };
    }
  },
  modules: {
    a: moduleA
  }
});

在页面中使用模块内的内容,$store.state.a.name

<template>
  <div id="app">
    <h1>---------APP module-------</h1>
    <h2>{{ $store.state.a.name }}</h2>
    <h2>{{ $store.getters.fullName }}</h2>
    <h2>{{ $store.getters.fullName2 }}</h2>
    <h2>{{ $store.getters.fullName3 }}</h2>
    <button @click="change">修改</button>
    <button @click="asyncChange">异步修改</button>
  </div>
</template>
 change() {
      this.$store.commit("updateName", "希瓦娜");
    },
    asyncChange() {
      this.$store.dispatch("changeName", "索尔");
    }

打印的context内容为
包含根状态下的内容,rootGetters以及rootState
在这里插入图片描述

vuex代码重构,抽离

在store文件夹下建立对应文件,将对应内容写入导出export
在index.js中引入使用
一般state不进行抽离
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值