vuex数据请求(state,actions,mutations,modules,getters)步骤详解

数据请求闭环:

1、在页面中通过事件触发一个函数

<template>
  <div>
      <button @click="fun()">点击获取数据</button>
  </div>
</template>

<script>
export default {
methods:{
  fun(){
    this.$store.dispatch("link",{url:"/data/link"})
  }
}
}
</script>
<style>
</style>

2、通过dispatch触发一个actions

created(){
        this.$store.dispatch("link",{url:"/data/link"})
    }

3.编写对应的actions

  actions: {
    getaxios(){
      
    }
  }

4、引用数据请求并且发送

5.发送异步操作

6.把请求来的数据交给mutations来修改state

import Vue from 'vue'
import Vuex from 'vuex'
// 4.引用数据请求
import getlink from "@/apis/getapi.js"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {//创建数据的类似于组件中的data

  },
  mutations: {
  },
  actions: {
    // 3编写对应的actions
    getaxios(context,payload){
      console.log(context)
      // 5.发送异步操作
      getlink(payload.url).then((ok)=>{
        console.log(ok.data.data)
        // 6.把请求来的数据交给mutations来修改state
        context.commit("uparr",{arrdata:ok.data.data})
      })
    }
  },
  modules: {
  }
})

 7、创建对应的mutations

 // 7创建对应的mutations
    uparr(state,payload){
      // 8把请求来的数据修改state
      state.arr=payload.arrdata
    }

8、页面显示

<template>
  <div>

//取值方式1
{{this.$store.state.arr}}

<h1>-----</h1>

// 取值方式2
{{newarr}}

  </div>
</template>

<script>
export default {
    // 取值方式2
    computed:{
        newarr(){
            return this.$store.state.arr
        }
    },
    //   <!-- 1.页面中通过事件触发一个函数 -->
    created(){
        // 2.通过dispatch触发一个actions
        this.$store.dispatch("getaxios",{url:"/data/one"})
    }
}
</script>

<style>

</style>


版权声明:本文为cxy_pan0913原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。