1. 程式人生 > 其它 >從零開始學VUE之VueX(actions)

從零開始學VUE之VueX(actions)

actions

非同步修改狀態資訊,比如Ajax

import Vue from 'vue'
// 匯入vuex
import Vuex from 'vuex'

import {INCR} from "./type";

// 通過vue安裝vuex
Vue.use(Vuex)

/**
 * 建立store
 * @type {Store<{counter: number}>}
 */
const store = new Vuex.Store({
  // 用於定義屬性
  state:{
    counter:1000
  },
  // 定義用於修改屬性的函式 同步提交
  mutations:{
    [INCR](state){
      state.counter
+=100; }, // 第一個引數是 state modifyCounter(state){ state.counter--; }, // 傳遞引數 modifyCounterVal(state,val){ state.counter += val; } }, // 計算屬性也就是getters 用於獲取 getters:{ // 獲取平方 getCountPF(state) { return state.counter * state.counter; }, // 獲取 平方的2分之一
getCountTwoOne(state, getters) { return getters.getCountPF / 2; }, // 獲取 平方的n分之一 引數傳遞 getCountN(state,getters){ return function (n){ return getters.getCountPF / n; } } }, // 用於處理非同步狀態修改 actions:{ updateInfo(context,playod){ // console.log(playod)
// // 模擬網路請求 // setTimeout(() => { // // 傳參 // console.log(playod.message); // // action 呼叫 mutations 修改 // context.commit(INCR); // // 回撥 // playod.success(); // },1000) /** * 返回 Promise,讓外面可以通過then捕獲返回結果 */ return new Promise((resolve,reject) => { // 模擬網路請求 setTimeout(() => { // 傳參 console.log(playod.message); // action 呼叫 mutations 修改 context.commit(INCR); // 回撥 resolve("ajax return data!") },1000) }) } } }) export default store

app.vue

<template>
  <div id="app">
    <h2>訪問store</h2>
    <h3>{{ $store.state.counter }}</h3>
    <!--    通過commit傳入方法呼叫-->
    <button @click="$store.commit('modifyCounter')">通過mutation修改狀態</button>
    <!--    傳遞引數-->
    <button @click="$store.commit('modifyCounterVal',5)">傳遞引數</button>
    <!--    常量方法-->
    <button @click="incr">常量方法</button>
    <!--    網路請求修改-->
    <button @click="ajaxCommit">網路請求修改</button>
    <button @click="ajaxCommitParam">網路請求修改(傳遞引數)</button>
    <h2>獲取Counter的平方</h2>
    <h2>{{ $store.getters.getCountPF }}</h2>
    <h2>獲取Counter的平方 2/1</h2>
    <h2>{{ $store.getters.getCountTwoOne }}</h2>
    <h2>獲取Counter的平方 n/1</h2>
    <h2>{{ $store.getters.getCountN(5) }}</h2>
  </div>
</template>

<script>
import TabBar from "./components/tabbar/TabBar";
import {INCR} from "./sotre/type";

export default {
  name: 'App',
  components: {
    TabBar
  },
  methods: {
    incr() {
      this.$store.commit(INCR);
    },
    ajaxCommit() {
      // 呼叫網路請求修改狀態
      this.$store.dispatch("updateInfo");
    },
    ajaxCommitParam() {
      // 呼叫網路請求修改狀態
      // this.$store.dispatch("updateInfo", {
      //   message:'我是引數',
      //   success(){
      //     console.log("回撥引數列印")
      //   }
      // });
      this.$store.dispatch("updateInfo", {
        message:'我是引數'
      }).then(res => {
        console.log(res)
      });
    }
  }
}
</script>

<style>
@import "./assets/css/base.css";
</style>

作者:彼岸舞

時間:2021\06\28

內容關於:VUE

本文屬於作者原創,未經允許,禁止轉發