####書到用時方恨少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
nodejs
寫的,數據庫須要用到mongodb
nodejs
和mongodb
,不過不要緊,照着文檔先用起來,問題不大。1.1 到MongoDB官網,下載適合的版本,安裝好 1.2 到後臺項目文件夾下,cmd,用npm start啓動數據庫
###2. 使用 postman 測試數據git
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
axios
:import 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
:import 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的學習,起初不是怎麼會用,看了官方文檔也沒怎麼懂,看了幾篇博客知道了一些使用方法,視頻中對這部分的構建仍是去年的形式,我照着如今的形式搭建了一下,由於只知其一不知其二,這也形成一些問題,好在目前遇到的問題都解決了,問題不大,後面還須要繼續深刻學習。
vue-cli
main.js
中配置好 import store from './store/store'
,而且在store.js
中引用import Vuex from 'vuex'
和使用Vue.use(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 }
mapState
、mapMutations
、mapAction
,vuex最簡單、最詳細的入門文檔,這篇文章寫的很是好,具體的就不展開了,直接使用起來,問題不大。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>
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>
###6. 結束數據庫
感受這個部分是最難的部分了,仍是不熟悉的緣由,下面都是邏輯處理方面的內容了