1. 程式人生 > >Vue-admin工作整理(十): actions(模擬接口請求實現組件字段更新)

Vue-admin工作整理(十): actions(模擬接口請求實現組件字段更新)

接口 pan iba 參數 pac template 時間 stat 增加

思路:通過提交一個 mutation,而不是直接變更狀態,它可以包括異步操作,通過請求接口,定義一個方法,第一個參數為對象,在裏面能夠提取到一些東西,比如:commit,這是一個方法,調用這個commit去提交一個mutation

  技術分享圖片  

import { getAppName } from ‘@/api/app‘

const actions = {
  // 請求接口,修改appName字段數據,定義一個updateAppName方法,第一個參數為對象,在裏面能夠提取到一些東西,比如:commit,這是一個方法,
  // 調用這個commit去提交一個mutation,“{ commit }”寫法為es6的方式,它相當於獲取到的是一個params對象。
  
// upadateAppName ({ commit }) { // // es6的函數 // getAppName().then(res => { // 模擬一個異步請求, // const { info: { appName } } = res // es6的寫法 // commit(‘setAppName‘, appName) // }).catch(err => { // console.log(err) // }) async updateAppName ({ commit }) { // es8的回調函數 console.log({ commit })
try { const { info: { appName } } = await getAppName() commit(‘setAppName‘, appName) } catch (err) { console.log(err) } } } export default actions
<template>
  <div>
    <a-input v-model="inputValue"/>
    <p>{{ inputValue }} -> lastLetter is {{ inputValueLastLetter }}</p>
    <p>appName: {{ appName }} -> appNameWithVersion is {{ appNameWithVersion }}</p>
    <p>userName: {{ userName }} -> firstLetter is {{ firstLetter }}</p>
    <a-show :message = "inputValue"/>
    <p><button @click="handleChangeAppName">修改appName</button></p>
    <p>{{ appVersion }}</p>
    <p><button @click="handleChangeUserName">修改用戶名</button></p>
  </div>
</template>
<script>
import
AInput from ‘_c/AInput.vue‘ import AShow from ‘_c/AShow.vue‘ import { mapState, mapGetters, mapMutations, mapActions } from ‘vuex‘ export default { name: ‘store‘, data () { return { inputValue: ‘‘ } }, components: { AInput, AShow }, computed: { ...mapState({ appName: state => state.appName, userName: state => state.user.userName, appVersion: state => state.appVersion }), ...mapGetters([ ‘appNameWithVersion‘, ‘firstLetter‘ ]), inputValueLastLetter () { return this.inputValue.substr(-1, 1) } }, methods: { ...mapActions([ ‘updateAppName‘ ]), ...mapMutations([ ‘setAppName‘, ‘setAppVersion‘, ‘setUserName‘ ]), handleChangeAppName () { // this.$store.commit(‘setAppName‘, { // appName: ‘newAppName‘ // }) // this.$store.commit(‘setAppVersion‘) this.setAppName({ appName: ‘apache‘ }) this.setAppVersion(‘V 2.0.2‘) // console.log(this.$store) // console.log(this.updateAppName) this.updateAppName() }, handleChangeUserName () { this.setUserName({ userName: ‘alibaba‘ }) } } } </script>

總結:

  1、mapActions是一個方法,註意它的定義位置不能放在computed裏,這樣會重復調用,產生 is not faction的現象

  2、action有異步調用,註意增加時間等待的方法

Vue-admin工作整理(十): actions(模擬接口請求實現組件字段更新)