1. 程式人生 > >vuejs2.0關於用axios結合vuex開發

vuejs2.0關於用axios結合vuex開發

vuex:index.js,   actions.js,     mutations.js,       getters.js

1.index.js中

import Vuex from 'vuex'
import Vue from 'vue'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'

Vue.use(Vuex)
let state = {
  user_msg: '',
  bugle: ''
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  getters
})

2.actions.js

原型匯入axios,在vuex中仍然不能用,需要再次匯入一遍,

import axios from 'axios'
export default {
  async loginGetUser ({commit,state},nameVal) {
    let _this = this
    let url = "http://www.xxxx.cn/test/ag/register.php?name="+nameVal
    await fetch(url)
      .then(res => res.json())
      .then(data => {
        this.commit('changUserMsg',data)
      })
      .catch( res => {
        _this.commit('changUserMsg',{msg:'fail'})
      })
  },
  saveForm({commit,state},url){
    console.log('url.....')
    console.log(url)
    axios({
      method:'get',
      url:url
    })
      .then(function (data) {
        console.log(data)
      })
      .catch(function (err) {
        console.log(err)
      })
  }

}



3.頁面元件呼叫方法

async test(){
             
          let url = "http://www.xxxg.cn/test/ag/queryClothes.php";
          await this.$store.dispatch('saveForm',url);
        },

無關的:

mutations.js

export default {
  changUserMsg ({state},data) {
    this.state.user_msg =data
  },
  
}