vue實戰(4):postman測試數據、封裝ajax、使用vuex管理狀態

####書到用時方恨少html

這個階段涉及到了vuex,原本想着不慌,用起來,使用的過程當中問題還真很多 本篇涉及到的內容: ---postman 測試數據 ---封裝 ajax 請求函數 ---封裝接口請求函數 ---使用 vuex 管理狀態 ---獲取首頁相關數據vue

###0. 其它 vue實戰(1):準備與資料整理 vue實戰(2):初始化項目、搭建底部導航路由 vue實戰(3):底部導航顯示、搭建各模塊靜態頁面、添加登陸頁頁面與路由 vue實戰(4):postman測試數據、封裝ajax、使用vuex管理狀態 vue實戰(5):總結一 vue實戰(6):異步顯示數據、開發Star組件 vue實戰(7):完整開發登陸頁面(一) vue實戰(8):完整開發登陸頁面(二) vue實戰(9):總結二 vue實戰(10):開發店鋪詳情(一)node

###1. 安裝 MongoDB ,啓動後臺ios

  • 這個小練習項目是一個先後臺分離的項目,後臺應用負責處理前臺應用提交的請求, 並給前臺應用返回 json 數據,前臺應用負責展示數據, 與用戶交互, 與後臺應用交互。
    • 後臺應用是用nodejs寫的,數據庫須要用到mongodb
    • 暫時不會nodejsmongodb,不過不要緊,照着文檔先用起來,問題不大。
    • MongoDB 官方網站連接 和 教程與安裝連接
1.1 到MongoDB官網,下載適合的版本,安裝好
1.2 到後臺項目文件夾下,cmd,用npm start啓動數據庫

啓動數據庫

###2. 使用 postman 測試數據git

  • 數據庫打開之後,進一步去測試是否打開成功,是否能取到數據,這裏就要用到接口測試工具 postman
  • postman 能夠獲取數據、能夠檢測API文檔中的接口是否有問題
  • 項目重點也不在這裏,能夠去 postman 官方網站連接 下載客戶端 和 很厲害的教程連接
  • 查看API接口文檔
1.1 根據經緯度獲取位置詳情(例子)
    --請求URL:http://localhost:3000/position/:geohash
    --示例:http://localhost:3000/position/40.10038,116.36867
    --請求方式:GET
    --參數類型:param
    |參數		  |是否必選   |類型       |說明
	|geohash    |Y         |string    |經緯度
    --返回示例:
    {
      "code": 0,
      "data": {
        "address": "北京市昌平區337省道",
        "city": "北京市",
        "geohash": "40.10038,116.36867",
        "latitude": "40.10038",
        "longitude": "116.36867",
        "name": "昌平區北七家宏福科技園(337省道北)"
        }
     }
1.2 接口輸入postman中,查看結果
1.3 輸出與文檔相同,獲取數據成功

數據獲取成功

###3. 封裝 ajax 請求函數ajax

  • 這裏的異步交互使用的是axios,須要在項目中添加依賴 npm install --save axios
  • 這裏的封裝很是重要,雖然代碼不是很難懂,可是感受是 知其然而不知其因此然 ,這也是貫徹了模塊化開發的思想,仍是先用起來,會熟能生巧的。
    • api 文件夾下建立 ajax.js ,引入 axiosimport axios from 'axios'
import axios from 'axios'
/*
 ajax請求模塊
 封裝ajax請求函數
 */
export default function ajax (url = '', data = {}, type = 'GET') { // type 默認傳 get
  return new Promise(function (resolve, reject) { // 返回 new promise,後面會用到 async 和 await
    let promise
    if (type === 'GET') { // 判斷 get
      let dataStr = '' // 數據拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') { // 拼接成 url 地址
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // 發送get請求
      promise = axios.get(url)
    } else {
      // 發送post請求
      promise = axios.post(url)
    }
    promise.then(response => {
      resolve(response.data)
    })
      .catch(error => {
        reject(error)
      })
  })
}

###4. 封裝接口請求函數mongodb

  • ajax 請求封裝完成以後,就是開始封裝各個接口請求函數
    • api 文件夾下建立 index.js ,引入 ajaximport ajax from './ajax'
  • 這個就好理解的多,根據項目需求的不一樣,須要的接口會很是的多,這樣作也是模塊化的體現,便於管理和維護
/* 包含多個模塊ajax函數
* 封裝接口請求函數(一部分例子)
* */
import ajax from './ajax'
const BASE_URL = '/api'  // 關於跨域

// 一、根據經緯度獲取位置詳情
// 此處直接這麼寫,當請求時會出錯,由於後臺代碼的端口是4000(或域名),與本地的請求端口不一致,天然沒法實現跨域ajax請求,須要代理配置
// export const reqAddress = (geohash) => ajax(`/position/${geohash}`) 
export const reqAddress = (geohash) => ajax(`${BASE_URL}/position/${geohash}`)
// 二、獲取食品分類列表
export const reqCategorys = () => ajax(`${BASE_URL}/index_category`)
// 三、根據經緯度獲取商鋪列表
export const reqShops = (latitude, longitude) => ajax(`${BASE_URL}/shops`, { latitude, longitude })
  • 此處涉及到跨域的問題,須要進行一些配置
    • 由於本項目使用vue-cli3腳手架搭建,沒有現成的配置文件,如今須要在根目錄下建立 vue.config.js,查了一些資料,有點雜並且比較落後,其中一些參數已經被棄用了,配置了一個簡潔的,其它配置能夠看 官方文檔
// vue.config.js
module.exports = {
  // 修改的配置
  publicPath: '/',
  devServer: {
    proxy: {
      '/api': { // 匹配全部以 '/api'開頭的請求路徑
        target: 'http://localhost:4000', // 代理目標的基礎路徑
        changeOrigin: true, // 支持跨域
        // ws: true,
        pathRewrite: { // 重寫路徑: 去掉路徑中開頭的'/api'
          '^/api': ''
        }
      }
    }
  }
}
  • 配置完成,測試一下是否可以取到數據,能夠在 App.vue 中引入 import { reqCategorys } from './api',添加mounted方法
async mounted () {  // 例子
    const result = await reqCategorys()
    console.log(result) // 打印輸出
  }

數據獲取成功 ###5. 建立 vuex 總體結構,管理狀態vuex

關於vuex的學習,起初不是怎麼會用,看了官方文檔也沒怎麼懂,看了幾篇博客知道了一些使用方法,視頻中對這部分的構建仍是去年的形式,我照着如今的形式搭建了一下,由於只知其一不知其二,這也形成一些問題,好在目前遇到的問題都解決了,問題不大,後面還須要繼續深刻學習。 modules文件夾裏面放模塊,更便於管理與維護vue-cli

  • 首先是下載依賴,而且在main.js中配置好 import store from './store/store',而且在store.js中引用import Vuex from 'vuex'和使用Vue.use(Vuex)
    • 若是在建立項目時已經配置好 vuex ,則無需在main.js中配置,已是配置好的了
// vuex最核心的管理對象store
import Vue from 'vue'
import Vuex from 'vuex'

// 引用模塊
import msite from './modules/msite' 
import getters from './getters'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    msite // modules文件夾中的msite模塊
  },
  getters
})
  • 模塊的編寫(例子)
// 內容比較多,這邊能夠把類似或者功能相同的組成一個模塊,更方便維護
// 模塊文件在store.js中引用

import { // 引用封裝好的接口
  reqAddress,
  reqCategorys,
  reqShops
} from '../../api/index'

// 基礎數據狀態,如今在任何文件均可以引用,引用時 this.$store.xxx 便可
const state = {
  latitude: 40.10038, // 緯度
  longitude: 116.36867, // 經度
  address: {}, // 地址信息對象
  categorys: [], // 分類數組
  shops: [] // 商家數組
}

// 直接更改state的多個方法的對象,如今在任何文件均可以引用,引用時 this.$store.commit('xxxx')便可
const mutations = { 
  RECEIVE_ADDRESS: (state, { address }) => { // 接受地址
    state.address = address
  },
  RECEIVE_REQCATEGORYS: (state, { categorys }) => { // 接受食品分類數組
    state.categorys = categorys
  },
  RECEIVE_REQSHOPS: (state, { shops }) => { // 接受商家數組
    state.shops = shops
  }
}

// 與後臺交互的數據,如今在任何文件均可以引用,引用時 this.$store.dispatch('xxxx')便可
const actions = {
  // 異步獲取地址
  async getAddress ({ commit, state }) {
    // 發送ajax異步請求
    const geohash = state.latitude + ',' + state.longitude
    const result = await reqAddress(geohash)
    // 提交一個mutations
    if (result.code === 0) {
      commit('RECEIVE_ADDRESS', { address: result.data })
    }
  },
  // 異步獲取分類列表
  async getCategorys ({ commit }) {
    const result = await reqCategorys()
    if (result.code === 0) {
      commit('RECEIVE_REQCATEGORYS', { categorys: result.data })
    }
  },
  // 異步獲取商家列表
  async getShops ({ commit, state }) {
    const { latitude, longitude } = state
    const result = await reqShops({ latitude, longitude })
    if (result.code === 0) {
      commit('RECEIVE_REQSHOPS', { shops: result.data })
    }
  }
}

export default { // 把方法暴露出去
  namespaced: true,
  state,
  mutations,
  actions
}
  • vuex 構建好,下面是使用測試,在須要的地方使用
    • 這裏還涉及到了 vuex 的輔助函數,mapStatemapMutationsmapActionvuex最簡單、最詳細的入門文檔,這篇文章寫的很是好,具體的就不展開了,直接使用起來,問題不大。
    • 首先在App.vue中引入import { mapActions } from 'vuex',使用須要的方法
<script>
import FooterGuide from './components/FooterGuide/FooterGuide'
import { mapActions } from 'vuex'
export default {
  name: 'App',
  mounted () {
    // this.$store.dispatch('msite/getAddress')
    this.getAddress() // 這邊調用的方法,在瀏覽器的插件中會有一個很是清楚的展現
  },
  methods: {
    ...mapActions('msite', ['getAddress'])
  },
  components: {
    FooterGuide
  }
}
</script>

getAddress方法更改數據後存在於mutation

  • 如今咱們須要其中的 name 屬性數據,在Msite.vue中引用import { mapState } from 'vuex',添加 computed 方法:computed: { ...mapState('msite', ['address'])},而後就能夠愉快的使用了
<!--首頁頭部-->
<!--此處title使用強制綁定,取出 address 中的 name-->
    <HeaderTop :title = "address.name"> 
      <router-link class="header_search" slot="left" to="">
        <i class="iconfont iconfangdajing"></i>
      </router-link>
      <router-link class="header_login" slot="right" to="">
        <span class="header_login_text">登陸|註冊</span>
      </router-link>
    </HeaderTop>

state中的數據 取出name屬性並顯示

###6. 結束數據庫

感受這個部分是最難的部分了,仍是不熟悉的緣由,下面都是邏輯處理方面的內容了

點個讚唄!

相關文章
相關標籤/搜索