Vuex的使用

定义:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式, 采用集中式存储管理应用的所有组件的状态,解决多组件数据通V

Vuex一般用于保存数据,让数据保持一致性。

下面就是Vuex的使用:

1:先安装

npm install vuex@next --save
yarn add vuex@next --save

2:配置

新建store文件->index.js,进行如下配置

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 数据
  },
  getters: {
    // 获取数据
  },
  mutations: {
    // 定义修改state的方法
  },
  actions: {
    // 操作异步方法
  },
  modules: {}
})

3: 在组件中使用 (完整代码)

vue2的写法

​<template>
  <div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'meetingView',
  computed: {
    ...mapState({
      dim: state => state.meeting.dim
    })
  },
  methods: {
    toDay() {
      // setDim 对应mutations定义的方法,date是对应的参数
      this.$store.commit('setDim', 'date')
    }
  }
}
</script>
<style lang="scss" scoped></style>

vue3的写法

​<template>
  <div>
  </div>
</template>

<script lang="ts">
import { mapState } from 'vuex'

setup(props, context) {
  const store = useStore()

  const dim = state.meeting.dim
    return store.state.meeting.dim
  }

  const toWeek = () => {
    store.commit('setDim', 'week')
  }
  return {
    dim,
    toWeek 
  }
}
</script>
<style lang="scss" scoped></style>

​

新建store文件->meeting.js(自定义),进行如下配置

  export default {
  state: {
    dim: 'home'
  },
  mutations: {
    setDim(state, val) {
      state.dim = val
    }
  }
}

 新建store文件->index.js,进行如下配置

import Vue from 'vue'
import Vuex from 'vuex'
import meeting from './meeting'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    meeting 
  }
})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值