Vuex在子组件中的使用

本文介绍了Vuex的使用方式,包括如何通过模块化管理登录状态,以及state数据的四种访问方法。同时,详细阐述了mutation和action的提交方式,强调了mutation的同步性质和action的异步操作特性。通过示例代码展示了如何在组件中便捷地使用Vuex进行状态管理和更新。

vuex推荐使用方式

index.js内容:

import Vue from 'vue'
import Vuex from 'vuex'
import login from './login'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    login: login
  }
})
export default store

 login.js内容:

export default {
  state: {},
  mutations: {},
  actions: {},
  modules: {}
}

这样有利于分离数据,不至于与其他页面数据混淆,简单明了,

state数据的四种使用方法

// 第一种
<div class='containerBox'>
    {{$store.state.login.name}}
  </div>


// 第二种
computed: mapState({
  name: state => state.login.name
}),


// 第三种
import { mapState } from 'vuex'
  computed: {
    ...mapState(['login']),
  },


// 第四种
  computed: {
    name () {
      return this.$store.state.login.name
    }
  },

Mutation 更改 Vuex 的 store 中的状态的唯一方法 (只能提交必须是同步操作)

store内容

state: {
    name: 'admin',
    password: '111111'
  },
  mutations: {
    SET_PASSWORD (state, data) {
      state.password = data
    }
  },
  actions: {
    set_password ({ commit }, data) {
      commit('SET_PASSWORD', data)
    }
  },




第一种
this.$store.commit('SET_PASSWORD', '2222')


第二种
import {mapMutations} from 'vuex'
methods: {
    ...mapMutations([
      'SET_PASSWORD' // 将 `this.SET_PASSWORD()` 映射为 `this.$store.commit('SET_PASSWORD')`
     ])
  }),
    pssword () {
      console.log(this.$store.state.login.password)
      this.SET_PASSWORD('2222')
      console.log(this.$store.state.login.password)
    }
  },


第三种
import { mapMutations} from 'vuex'
methods: {
    ...mapMutations({
      setPassword: 'SET_PASSWORD' // 将 `this.setPassword()` 映射为 `this.$store.commit('SET_PASSWORD')`
    }),
    pssword () {
      console.log(this.$store.state.login.password)
      this.setPassword('2222')
      console.log(this.$store.state.login.password)
    }
  },

第四种是通过Actions的来提交

Actions:

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
store内容

state: {
    name: 'admin',
    password: '111111'
  },
  mutations: {
    SET_PASSWORD (state, data) {
      state.password = data
    }
  },
  actions: {
    set_password ({ commit }, data) {
      commit('SET_PASSWORD', data)
    }
  },



第一种
this.$store.dispatch('set_password', '3333')


第二种
import { mapActions } from 'vuex'
methods: {
    ...mapActions(['set_password']),
    pssword () {
      this.set_password('222')
      console.log(this.$store.state.login.password)
    }
  },



第三种
import { mapActions } from 'vuex'
    ...mapActions({
      setPassword: 'set_password' // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    }),

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cdlblbq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值