action异步传输

action异步传输

import { createStore } from 'vuex'

export default createStore({
  //data
  state: {
     num:0,
     username:'农夫山泉有点甜',
     password:123456,
     duanzis:null
  },
  getters: {
    reverseMsg:function(state){
      return state.username.split('').reverse().join('')
    },
    mixinMsg:function(state){
      return function(val){
        return val+state.password
      }
    }
  },
  //methods 处理状态
  mutations: {
    addNum(state){
      state.num+=2
    },
    setNum(state,value){
      state.num = value
    },
    setDuanzi:function(state,value){
      state.duanzis = value
    }
  },
  //异步方法
  actions: {
    setDz:function(content){
      let httpUrl ='https://api.apiopen.top/musicRankings'
    fetch(httpUrl).then(res=>res.json()).then(res=>{
      console.log(res);
      console.log(content);
      //通过muation来设置state
      content.commit('setDuanzi',res.result)
    })
    }
  },
  //模块
  modules: {
  }
})

<template>
  <div>
      <h1>action</h1>
      <h1>{{num}}</h1>
      <button @click="addNum">添加Num</button>
      <button @click="getDuanzi">点击获取段子1</button>
      <button @click="setDz">点击获取段子2</button>
        <ul>
            <li v-for=" (item,index) in duanzis " :key="index">{{index}}:{{item.name}}</li>
        </ul>
        
  </div>
</template>

<script>

import {mapState,mapActions,mapMutations} from 'vuex'
let mapStateObj = mapState(['duanzis','num'])
let mapActionsObj = mapActions(['setDz'])
let mapMutationsObj = mapMutations(['addNum','setNum'])
export default {
    computed: {
        ...mapStateObj
    },
    methods:{
        getDuanzi:function(){
            this.$store.dispatch('setDz')
            console.log(this);
        },
        ...mapActionsObj,
        ...mapMutationsObj 
    }
}
</script>

<style>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Vue1024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值