小案例学习Vuex

小案例学习Vuex

须知:

Vuex是什么呢?是用来干嘛的呢?
官方的解释:Vuex(官网链接)是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
大白话就是:vue里多处用到操作到的数据都可以丢给他→Vuex(模糊讲解勿喷,哈哈)

案例:

效果图

1、首先你的有一个vue的项目!然后下载并安装Vuex:

npm install vuex --save

2、在src下面创建store文件夹大致框架如下:

store初始代码

3、在main.js里面引入Vuex和store文件夹:

main.js引入文件
//vuex 引入
import store from "./store";
import Vuex from 'vuex'
Vue.use(Vuex)
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

4、页面写入代码:

<template>
  <div class="home">
    <h1>这是个"栗子"</h1>
    <button class="button" @click="add">+</button>
    <span>这是vuex里的数据{{value}}</span>
    <button class="button" @click="reduce">-</button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      //获取vuex里state的值 his.$store.state.数据的键名
      value: this.$store.state.num,
    }
  },
  methods:{
    add(){
      // mutation是通过commit函数来执行的,只负责改变数据,不负责刷新数据
      this.$store.commit("plus"); 
      //需要通过getters来重新获取数据
      this.value = this.$store.getters.optCount
    },
    reduce(){
      this.$store.commit("minus",{idx:2}); 
      this.value = this.$store.getters.optCount
    },
  }
};
</script>
<style>
.button{
  width: 30px;
  height: 30px;
  background-color: coral;
  border: 0;
}
</style>

5、store下index.js代码如下:

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
  //  state 就类似vue组件的 data ,专门用来存储数据的
  state: {
    num:1
  },
  // 注意:如果要 state 里面的值,只能通过 调用 mutations 提供的方法,才能操作对应的数据
  //不推荐直接操作 state 中的数据,万一导致了数据的紊乱,怕你不能快速定位到错误;
  mutations: {
    //方法中有两个参数,1-- state状态; 2-- 通过commit 传来的参数;
    plus(state){
      state.num ++
    },
    minus(state,idx){
      state.num -= idx.idx
    }
  },
  // getters在此只为对外面提供数据,不修改数据
  getters:{
    optCount: function (state) {
      return state.num
    }
  },
  actions: {},
  modules: {}
});

总结Time:

Vuex 主要有四部分:
1.state:包含了store中存储的各个状态。
2.getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
3.mutation: 一个方法,mutation是改变状态的执行者。mutation用于同步地更改状态。
4.action: 一个方法,异步地更改状态,需要使用action。action并不能直接改变state,而是发起mutation。大白话:异步操作。

注意:

1.state中的数据,不能直接修改,如果想要修改,必须通过 mutations
2.如果组件想要直接 从 state 上获取数据: 需要 this.$store.state.xxx(数据的键名)
3.如果 组件,想要修改数据,必须使用 mutations 提供的方法,需要通过 this.$store.commit ('方法的名称', 唯一的一个参数)
4.如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters. 方法名

小结:

文章为本人学习小总结,如有写的不妥之处请多多包含指导。
文章内容部分借鉴作者:七分热度丶 新手上路加油(ง •_•)ง

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。