vue学习-mapState,mapGetters,mapActions,mapMutations

mapState,mapGetters,mapActions,mapMutations

利用以上四个方法可以简化页面中的引用方式。注意使用方法!

<template>
   <div>
     <h1>姓名:{{$store.state.username}}</h1>
     <h1>年龄:{{$store.state.age}}</h1>
     <h1>新的年龄:{{$store.getters.newage}}</h1>
     <button @click="addAge(5)">添加年龄</button>

     <h1>姓名:{{username}}</h1>
     <h1>年龄:{{age}}</h1>
     <h1>新的年龄:{{newage}}</h1>
     <ul>
         <li v-for="(item,i) in infolist" :key="i">
        <h3>{{item.name}}</h3>
        <P>{{item.text}}</p>
        </li>
     </ul>
   </div>
</template>

<script>
//辅助函数
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
export default{

 mounted(){
     console.log(this)
     //触发vuex的action方法
     //this.$store.dispatch('getSome')
     this.getSome();
   },
   methods:{
       ...mapActions(['getSome']),
       ...mapMutations(['addAge'])
     /*  addAge:function(){
           this.$store.commit('addAge',5)
       }*/
   },
   computed:{
       ...mapState(['username','age','infolist']),
       ...mapGetters(['newage'])
   }
}
  
</script>

store中的index.js为:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  //放置全局状态
  state: {
    username:"gulf",
    age:23,
    infolist:[]
  },
  //计算属性
  getters:{
    newage:function(state){
      return state.age+1
    }
  },
  //修改数据/状态的方法
  mutations: {
    //payload参数
    addAge(state,payload){
      state.age+=payload;
    },
    setList(state,payload){
      state.infolist=payload;
    }
  },
  //异步修改数据
  actions: {
      //去请求一个服务器接口
      getSome(context){
        let httpUrl='https://api.apiopen.top/getJoke?page=1&count=10&type=video'
        fetch(httpUrl).then((res)=>{
          return res.json()
        }).then((res)=>{
          console.log(res);
          context.commit('setList',res.result);
        })
      }
  },
  //vuex细分模块
  modules: {
  }
})

结果如下
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值