5分钟带你入门vuex(vue状态管理)

如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,那么接下来我们就来学习一下vuex是如何修改状态值的 。

在你的项目目录下,使用命令:vue create vue-demo 新建一个VUE项目。

然后进入项目目录,cd vue-demo 安装VUEX,npm install vuex --save

然后我们在项目的src目录下新建一个目录store,在该目录下新建一个index.js文件,这个文件是我们用来创建vuex实例。再然后在该文件中引入vue和vuex,创建Vuex.Store实例保存到变量store中,最后使用export default导出store 。代码如下

import Vue from 'vue';
import Vuex from 'vuex';
// 使用VUEX
Vue.use(Vuex);
// 创建VUEX实例
const store = new Vuex.Store({

});

export default store;

然后我们在main.js文件中引入该文件,在文件里面添加 import store from './store';,再在vue实例全局引入store对象; 代码如下

import Vue from 'vue'
import App from './App.vue'
import store from './store';
import router from './router';

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store,
  router
}).$mount('#app')

到此,我们就可以开始编写我们的vuex业务代码了,那么,我们的数据如何保存?

State

vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据;

import Vue from 'vue';
import Vuex from 'vuex';
// 使用VUEX
Vue.use(Vuex);
// 创建VUEX实例
const store = new Vuex.Store({
  state: {
    count: 1
  }
});

export default store;
<template>
  <div id="app">
    {{this.$store.state.count}}
  </div>
</template>

<script>

export default {
  name: 'app',
  components: {
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

这时候我们页面上就得到了这个count值1

Getters

Getter相当于vue中的computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,这里我们可以通过定义vuex的Getter来获取,Getters 可以用于监听、state中的值的变化,返回计算后的结果,这里我们修改app.vue文件如下:

<template>
  <div id="app">
    {{this.$store.state.count}}
    {{this.$store.getters.getStateCount}}
  </div>
</template>

<script>

export default {
  name: 'app',
  components: {
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

再修改store/index.js文件如下,其中getters中的getStateCount方法接收一个参数state,这个参数就是我们用来保存数据的那个对象;

import Vue from 'vue';
import Vuex from 'vuex';
// 使用VUEX
Vue.use(Vuex);
// 创建VUEX实例
const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getStateCount: state => {
      return state.count + 1
    }
  }
});

export default store;

然后就可以在页面看效果了。

Mutations

数据我们在页面是获取到了,但是如果我们需要修改count值怎么办?如果需要修改store中的值唯一的方法就是提交mutation来修改,我们现在App.vue文件中添加两个按钮,一个加1,一个减1;这里我们点击按钮调用addFun(执行加的方法)和reductionFun(执行减法的方法),然后在里面直接提交mutations中的方法修改值:

<template>
  <div id="app">
    {{this.$store.state.count}}
    {{this.$store.getters.getStateCount}}
    <button @click="addFn">加</button>
    <button @click="reductionFun">减</button>
  </div>
</template>

<script>

export default {
  name: 'app',
  components: {
  },
  menthod: {
    addFn() {
      this.$store.commit('add')
    },
    reductionFun() {
      this.$store.commit('reduction')
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

修改index.js文件,添加mutations,在mutations中定义两个函数,用来对count加1和减1,这里定义的两个方法就是上面commit提交的两个方法如下:

import Vue from 'vue';
import Vuex from 'vuex';
// 使用VUEX
Vue.use(Vuex);
// 创建VUEX实例
const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getStateCount: state => {
      return state.count + 1
    }
  },
  mutations: {
    add(state) {
     state.count++ 
    },
    reduction(state) {
     state.count-- 
    },
  }
});

export default store;

到此,就可以去页面上看效果了。

Actions

我们看到,点击按钮时,页面上的值是改变了;我们达到了修改store中状态值的目的,但是,官方并不建议我们这样直接去修改store里面的值,而是让我们去提交一个actions,在actions中提交mutation再去修改状态值,接下来我们修改store/index.js文件,先定义actions提交mutation的函数:

import Vue from 'vue';
import Vuex from 'vuex';
// 使用VUEX
Vue.use(Vuex);
// 创建VUEX实例
const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getStateCount: state => {
      return state.count + 1
    }
  },
  mutations: {
    add(state) {
     state.count++ 
    },
    reduction(state) {
     state.count-- 
    },
  },
  actions: {
    // 接受一个与 store 实例具有相同方法和属性的 context 对象
    addFn(context) {
      context.commit('add')
    },
    // 接受一个与 store 实例具有相同方法和属性的 context 对象
    reductionFn(context) {
      context.commit('reduction')
    }
  }
});

export default store;

然后我们去修改App.vue文件:

<template>
  <div id="app">
    {{this.$store.state.count}}
    {{this.$store.getters.getStateCount}}
    <button @click="addFn">加</button>
    <button @click="reductionFun">减</button>
  </div>
</template>

<script>

export default {
  name: 'app',
  components: {
  },
  menthod: {
    addFn() {
      // this.$store.commit('add')
      this.$store.dispatch('addFn');
    },
    reductionFun() {
      // this.$store.commit('reduction')
      this.$store.dispatch('reductionFun');
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

这里我们把commit提交mutations修改为使用dispatch来提交actions;我们点击页面,效果是一样的。

好了,我们这里已经实现了一个基本的vuex修改状态值的完整流程,如果我们需要指定加减的数值,那么我们直接传入dispatch中的第二个参数,然后在actions中的对应函数中接受参数在传递给mutations中的函数进行计算 。

mapState、mapGetters、mapActions

如果我们不喜欢这种在页面上使用“this.$stroe.state.count”和“this.$store.dispatch(‘funName’)”这种很长的写法,那么我们可以使用mapState、mapGetters、mapActions就不会这么麻烦了;

我们修改App.vue文件如下:

<template>
  <div id="app">
    {{this.$store.state.count}}
    {{this.$store.getters.getStateCount}}
    <button @click="addFn">加</button>
    <button @click="reductionFun">减</button>
    {{resultNum}}
  </div>
</template>

<script>
import {mapState、mapGetters、mapActions} from 'vuex';
export default {
  name: 'app',
  components: {
  },
  computed: {
    ..mapState({
      resultNmu: state => state.count
    })
  },
  menthod: {
    addFn() {
      // this.$store.commit('add')
      this.$store.dispatch('addFn');
    },
    reductionFun() {
      // this.$store.commit('reduction')
      this.$store.dispatch('reductionFun');
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

到此,就可以去页面看效果了, 正常显示,效果是一样的,我们就可以不再使用很长的写法来调用了。

原创文章,作者:ZERO,如若转载,请注明出处:https://www.edu24.cn/course/vue/vuex-state.html

Like (0)
Donate 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
ZEROZERO
Previous 2019年8月16日
Next 2019年12月6日

相关推荐

  • 曾被问及的一些关于VUE的面试题

    由于没有系统的专研过VUE,关于VUE的一些理论知识点,没有去挖心思记忆及理解,只是在实际工作中知道怎么去使用。所以曾在面试的过程中被人嫌弃过,这一直是小编的痛点,/(ㄒoㄒ)/~…

    2022年4月2日
    730
  • 创建vue3 + typescript项目说明

    创建项目 选择Manually select features【手动配置】 如上图选择配置项,并在下一步,选择3.x 接下来,按照推荐设置,进行选择【推荐设置都已英文字母大写的形式…

    2023年11月23日
    463
  • vue3.0项目如何配置路径别名

    vue更新到3.0以后,在项目中已经深度集成了webpack,使用vue create命令新建项目之后,已经没有webpack配置文件了,这对于像小编这样没有系统学习过前端的同学来…

    2020年8月22日
    3.9K
  • Vue项目中实现用户登录及token验证

    在前后端完全分离的情况下,Vue项目中实现token验证大致思路如下: 第一次登录的时候,前端调后端的登陆接口,发送用户名和密码 。 后端收到请求,验证用户名和密码,验证成功,就给…

    2019年8月8日
    4.7K
  • 如何封装VUE组件库?

    之前一直在使用Angular开发项目,也封装过Angular组件。由于种种原因,现需要转战VUE。好在本人有扎实的实战经验,结合各位网络大神整理的经验,现总结一篇关于封装VUE组件…

    2019年7月31日
    2.2K

发表回复

Please Login to Comment