vuex的5个属性

  • vuex的5个属性 State、Mutation、Action、Module、Getter
  • 1 state => 存放共享的数据
    1.1 调用vuex中存储的数据方法
    方案一 从vuex中按需导入mapstate函数, 注意是在计算属性computed中使用
<script>
import { mapState } from 'vuex'
export default {
  // 计算属性
  computed: {
    // 使用 mapState 辅助函数帮助我们生成计算属性 可传入数组或者对象
    ...mapState({
      theme: (state) => state.settings.theme,
      sideTheme: (state) => state.settings.sideTheme,
      sidebar: (state) => state.app.sidebar,
      device: (state) => state.app.device,
      needTagsView: (state) => state.settings.tagsView,
      fixedHeader: (state) => state.settings.fixedHeader
    }),
  },
</script>

方案二 在标签中直接使用

<p>{{$store.state.模块名.全局数据名称}}</p>

方案三 在函数中调用

this.$store.state.模块名称.全局数据名称
或
this.$store.state.全局数据名称
  • 2 mutations => 存放更改数据的函数,第一个参数是state
 mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
     SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
  },

2.1 触发mutations里函数的方法
方案一 使用commit触发Mutations操作

this.$store.commit('SET_TOKEN','token')

方案二 从vuex中按需导入mapMutations函数,注意是在methods中使用

<script>
import { mapMutations } from 'vuex'
export default {
  // 方法
  methods: {
    // 使用 mapMutations 辅助函数帮助我们生成方法 传入由函数名组成的数组
    ...mapMutations(['SET_TOKEN']),
    this.SET_TOKEN('token')
  },
</script>
  • 3 actions => 存放异步更改数据的函数,再触发mutations里对应的函数
actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          const data = res.data
          commit('SET_TOKEN', data.access_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  }

3.1 触发actions里函数的方法
方案一 直接使用 dispatch触发Action函数

this.$store.dispatch('Login', this.loginForm).then(() => {
  this.$router.push({ path: this.redirect || '/' }).catch(() => {})
 })

方案二 从vuex中按需导入mapActions函数,注意是在methods中使用

<script>
import { mapActions } from 'vuex'
export default {
  // 方法
  methods: {
    // 使用 mapMutations 辅助函数帮助我们生成方法 传入由函数名组成的数组
    ...mapActions(['Login']),
    this.Login(this.loginForm).then(() => {
	  this.$router.push({ path: this.redirect || '/' }).catch(() => {})
	 })
  },
</script>
  • 4 modules => 模块化vuex,使每一个模块都有这5个属性在这里插入图片描述
  • 5 getters => 类似Vue的计算属性,对基础数据进行加工形成所需的数据,使用getters里面的数据this.$store.getters.属性名称(this.$store.getters.token)
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值