Vue——vue3中vuex映射状态数据和方法

1、配置

src\store\index.js配置文件

import { createStore } from 'vuex'

export default createStore({
  // 设置全局数据
  state: {
    count: 0,
    list: []
  },
  // 计算属性
  getters: {
    totalPrice (state) {
      return state.count * 100
    }
  },
  // 修改状态方法(同步)
  mutations: {
    // 无传参
    setCount (state) {
      state.count++
    },
    // 有传参,num为传入参数
    setCountNum (state, num) {
      state.count += num
    }setList (state, arr) {
      state.list = arr
    }
  },
  // 修改状态方法(异步)
  actions: {
    getList (context) {
      fetch('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=2').then(res => res.json()).then(result => {
        console.log(result, '接口返回数据');
        context.commit('setList', result)
      })
    }
  },
  modules: {
  }
})

2、引入

main.js文件

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

createApp(App).use(store).mount('#app')

3、使用

<template>
    <h1>数量-映射前:{{$store.state.count}}</h1>
    <h1>数量-映射后:{{count}}</h1>
    <h1>数量-映射后:{{maxCount}}</h1>
    <h1>总价-映射前:{{$store.getters.totalPrice}}</h1>
    <h1>总价-映射后:{{totalPrice}}</h1>
    <button @click="change">修改数量-映射前</button>
    <button @click="setCountNum(2)">修改数量-映射后</button>
</template>
<script>

import {mapState,mapMutations,mapActions,mapGetters} from 'vuex'
export default {
  computed:{
      // 映射后
    ...mapState(['count']),
      // 映射后
      // 自定义变量名
    ...mapState({
      maxCount:(state)=>state.count
    }),
      // 映射后
    ...mapGetters(['totalPrice'])
  },
  methods: {
      // 映射后
    ...mapMutations(['setCountNum']),
      // 映射后
    ...mapActions(['getList']),
      // 映射前
    change () {
      this.$store.commit('setCountNum', 10)
    }
  },
  mounted () {
    // 映射前
    // this.$store.dispatch('getList')
    // 映射后
    this.getList()
   
  }
}
</script>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值