Vuex 利用AJAX修改数据和映射之一

Vuex中同步的操作数据是在getters中完成的,异步操作在actions中完成
index.js
首先在state中定义需要存放的数组

state: {
    dzlist: [],
  },

mutations中定义个函数把取到的数组赋值给arr

 mutations: {
    //同步写法
    setDz: function (state, arr) {
      state.dzlist = arr;
    },
  },

在actions进行异步操作,执行ajax

 actions: {
    getDz: function (context) {
      let api = "https//api.XX";//所需要获取数据的api
      fetch(api)
        .then((res) => res.json())
        .then((result) => {
          console.log("result", result);//看返回什么结果
          context.commit("setDz", result.result);//commit提交数据
        });
    },
  },

Home.vue

<h1>段子</h1>
    <!--  得到的数据进行循环操作-->
 <p v-for="(item,i) in $store.state.dzlist" :key="i">{{ item.text }}</p>

为了不用每次写$store.state,可以通过引用mapState、mapMutations、mapActions..computed:{...mapState("count")}//映射到count,这样的话body中可以写为{{count}}了,或者可以修改count的名字,...maopState({productCount: (state) => state.count,})在body中可以写{{productCount}}

mounted() {//写在mounted中
    this.$store.dispatch("getDz");//获取数据用dispatch
  },

效果图:在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值