vuex的使用
Vuex 使用
2023-09-14 08:58:55 时间
vuex其实可以看成一个公共的数据仓库,从作用来说大致上可以看成是我们的cookie或者localStorage,下面我们来看看怎么使用吧
1.安装
vuex不是vue内置的所以需要额外安装
npm i vuex --save
2.设置仓库
在src下面新建一个文件夹,这里我新建一个store/index.js,内容大致为:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 0 } const mutations = { add (state, n) { state.count += n }, reduce (state, n) { state.count -= n } } const getters = { count2 (state) { return state.count + 100 } } const actions = { aAdd (context) { context.commit('add', 6) } } export default new Vuex.Store({ state, mutations, getters, actions })
3.引入使用
vuex实例可以被引入到Vue实例和Vue组件中,引入后可以在this.$store中使用vuex
<template> <div> <!-- 通过$store.state获取仓库数据 --> count:{{$store.state.count}}<br> <!-- 通过computed mapState来简化数据写法 --> count:{{count}}<br> count2:{{count2}} <!-- 通过$store.commit来触发仓库方法 --> <button @click="$store.commit('add', 10)">+</button> <!-- 通过methods mapMutation 来简化调用仓库方法 --> <button @click="reduce(2)">-</button><br> actions调用mutions的方法<button @click="aAdd">加</button> </div> </template> <script> import store from '@/store' import { mapState, mapMutations, mapGetters, mapActions } from 'vuex' export default { data () { return {} }, // 通过mapMutation来简化vuex数据获取 methods: { ...mapMutations(['add', 'reduce']), // 用传对象的形式可以更加灵活 //...mapMutations({ // count: state => state.count, // countAlias: 'count', // }) ...mapActions(['aAdd']) }, store, // 通过mapState来简化vuex数据获取 computed: { ...mapState(['count']), ...mapGetters(['count2']) // count2 () { // return this.$store.getters.count2 // } } // computed: mapState({ // count: state => state.count // }) // computed: { // count () { // return this.$store.state.count // } // } } </script>
ps:map系列的方法既可以传入数组,也可以传入对象的形式
vuex主要内容包括:state(相当于data)、mutations(相当于methods)、getter(相当于computed)、actions(这个是调用mutation用的)、modules(大型应用使用,这里不演示了)
相关文章
- VUE - vuex state的使用
- [Vuex] Create a Vuex Store using TypeScript
- [Nuxt] Build a Vue.js Form then use Vuex Actions to Post to an API in Nuxt
- [Vuex] Perform Async Updates using Vuex Actions with TypeScript
- [Nuxt] Build a Vue.js Form then use Vuex Actions to Post to an API in Nuxt
- 说说vuex的管理操作或理解
- localStorage 能实现 token 的存储需求,为啥还要存储在 Vuex 或 Redux 中呢?
- 前端开发:Vuex的基本使用
- 父组件中vuex方法更新state,子组件不能及时更新并渲染的解决方法
- 前端MVC Vue2学习总结(九)——Vuex状态管理插件
- Vue项目保持用户登录状态(localStorage + vuex 刷新页面后状态依然保持)
- Vue (完结篇)- Vuex 概念 、开启Apache的gzip压缩