2. vue項目2

1. axios封裝

// src/utils/axios.js
import axios from 'axios'

class HttpRequest {
  constructor() {
    // 接口地址(根據實際情況修改)
    this.baseURL = process.env.NODE_ENV === 'production' ? '/' : 'http://localhost:7001'
    this.timeout = 3000
    // loading 需要加 (一般項目不加判呕,在組件中加)
    this.queue = {}  // 專門用來維護請求隊列的压昼,做loading處理的
    // 頁面切換 需要取消請求
  }

  setInterceptor(instance, url) {
    instance.interceptors.request.use((config) => {
      // 開啟loading 一個頁面多個請求,只產生一個loading
      if (Object.keys(this.queue).length === 0) {
        // 開loading
      }

      // 可以記錄請求的取消函數
      let CancelToken = axios.CancelToken
      config.cancelToken = new CancelToken((c) => {  // 存到vuex中钧大, 頁面切換的時候翰撑,組件銷毀的時候執(zhí)行
        // c 就是當前取消請求的token
        console.log(c)
      })
      this.queue[url] = true
      return config  // 返回配置文件,請求的時候要用
    })

    // 攔截器
    instance.interceptors.response.use((res) => {
      delete this.queue[url]  // 一旦響應了 就從隊列刪除

      if (Object.keys(this.queue).length === 0) {  // 如果隊列有值
        // close loading
      }

      if (res.data.err === 0) {  // 根據實際接口調整 可swithCase 狀態(tài)
        return res.data.data
      } else {
        return Promise.reject(res.data)  // 失敗拋出異常
      }
    }, (err) => {
      delete this.queue[url]
      if (Object.keys(this.queue).length === 0) {  // 如果隊列有值
        // close loading
      }
      return Promise.reject(err)
    })

  }

  request(options) {  // 通過 request方法來進行請求操作
    // 每次請求可以創(chuàng)建一個新的實例啊央,如果業(yè)務不復雜眶诈,可以不創(chuàng)建實例,直接使用axios
    let instance = axios.create()
    let config = {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options
    }
    this.setInterceptor(instance, config.url)
    return instance(config)  // 產生的是一個 promise
  }
  get(url, data = {}) {
    return this.request({
      url,
      method: 'get',
      ...data
    })
  }
  post(url, data = {}) {
    return this.request({
      url,
      method: 'post',
      data
    })
  }
}

export default new HttpRequest

2. 請求輪播圖數據劣挫,并存到vuex中

    1. vuex流程第一步 state 定義變量
// src/store/modules/home/state.js
const homeState = {
  category: -1,
  slides: [],  // 接口返回的輪播圖數據
}

export default homeState
    1. 第二步 action-types 維護所有的動作
// src/store/action-types.js
// 所有的名字都列在這里
// 首頁
export const SET_CATEGORY = 'SET_CATEGORY'
// 輪播圖
export const SET_SLIDES = 'SET_SLIDES'
    1. 第三步 api
// src/api/home.js
import axios from '@/utils/axios'

// 設置接口 自己根據實際接口修改
export const fecthSlides = () => axios.get('/api/slider')

// 該接口返回數據:
// { err: 0,
//   data: [
//     {url: "http://www.xxx"},
//     {url: "http://www.xxx"}
//   ]
// }
    1. 第四步 actions 異步請求
// src/store/modules/home/actions.js
import * as Types from '@/store/action-types'
import { fecthSlides } from '@/api/home.js'

const homeActions = {
  async [Types.SET_SLIDES]({ commit }) {
    let slides = await fecthSlides()
    commit(Types.SET_SLIDES, slides)  // 交給mutation去更改狀態(tài)
  }
}

export default homeActions
    1. 第五步 mutations
// src/store/modules/home/mutations.js
import * as Types from '@/store/action-types'

const homeMutations = {
  [Types.SET_CATEGORY](state, payload) {  // 修改分類狀態(tài)
    state.category = payload
  },
  [Types.SET_SLIDES](state, slides) {
    state.slides = slides  // 更新輪播圖數據
  }
}

export default homeMutations
    1. 組件應用
// src/views/home/index.vue
<template>
  <div>
    <!-- v-model 相當于 :value="value" @input="change" -->
    <HomeHeader v-model="currentCategory"></HomeHeader>
    <van-swipe class="my-swipe" :autoplay="2000" indicator-color="white">
      <van-swipe-item v-for="(s, index) in slides" :key="index">
        <img :src="s.url" alt="" />
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script>
import HomeHeader from "./home-header.vue";
import { createNamespacedHelpers } from "vuex";
import * as Types from "@/store/action-types";

// 這里拿到的是 home 模塊下的
let {
  mapState: mapHomeState,
  mapMutations,
  mapActions,
} = createNamespacedHelpers("home");

export default {
  methods: {
    ...mapMutations([Types.SET_CATEGORY]),
    ...mapActions([Types.SET_SLIDES]),
  },
  mounted() {
    if (this.slides.length === 0) {
      // 如果vuex沒有數據才請求,有數據直接用
      this[Types.SET_SLIDES]();
    }
  },
  computed: {
    ...mapHomeState(["category", "slides"]), // 獲取vuex中的狀態(tài)綁定到當前的實例
    currentCategory: {
      get() {
        // 取值
        return this.category;
      },
      set(value) {
        // 修改狀態(tài)东帅,默認會調用mutation更改狀態(tài)
        this[Types.SET_CATEGORY](value);
      },
    },
  },
  components: {
    HomeHeader,
  },
  data() {
    return {
      value: -1, // 全部 -1, node 0, react 1, vue 2
    };
  },
};
</script>
<style lang="scss">
.my-swipe {
  height: 120px;
  img {
    height: 100%;
    width: 100%;
  }
}
</style>

3. 取消請求

當切換頁面的時候压固,之前的請求可以取消掉,因為沒有用了

    1. 定義公共的狀態(tài)tokens
// src/store/index.js
import Vue from "vue";
import Vuex from "vuex";
import modules from './modules/index.js'
import * as Types from '@/store/action-types'

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {  // 公共的狀態(tài)
    tokens: []
  },
  mutations: {
    [Types.SET_TOKEN](state, token) {
      // 我們希望狀態(tài)可以被追蹤
      state.tokens = [...state.tokens, token]  // 存儲token靠闭,頁面切換可以讓token依次執(zhí)行
    },
    [Types.CLEAR_TOKEN](state) {
      state.tokens.forEach(token => token())  // 執(zhí)行所有的取消方法帐我,都調用一下
      state.tokens = []  // 清空列表
    }
  },
  actions: {},
  modules: {
    ...modules
  },
});

export default store
    1. 設置token
// src/store/action-types.js
export const SET_TOKEN = 'SET_TOKEN'
export const CLEAR_TOKEN = 'CLEAR_TOKEN'
    1. 修改 axios
// src/utils/axios.js
import store from '../store'
import * as Types from '@/store/action-types'
instance.interceptors.request.use((config) => {
      // 開啟loading 一個頁面多個請求,只產生一個loading
      if (Object.keys(this.queue).length === 0) {
        // 開loading
      }

      // 可以記錄請求的取消函數
      let CancelToken = axios.CancelToken
      // 相當于 xhr.abort() 中斷請求的方法
      config.cancelToken = new CancelToken((c) => {  // 存到vuex中愧膀, 頁面切換的時候拦键,組件銷毀的時候執(zhí)行
        // c 就是當前取消請求的token
        store.commit(Types.SET_TOKEN, c)  // 同步將取消方法存入到vuex中
      })
      this.queue[url] = true
      return config  // 返回配置文件,請求的時候要用
    })
    1. 路由鉤子封裝檩淋,取消請求
// src/router/hooks.js
import store from "../store"
import * as Types from '@/store/action-types'

export default {
  // 'clear_token' 這個只是給自己看的芬为,沒有任何實際意義
  'clear_token': (to, from, next) => {
    // whiteList 可以添加一些白名單萄金,不清空
    store.commit(Types.CLEAR_TOKEN)  // 清空 token
    next()
  }
}
// src/router/index.js
import hooks from './hooks'
Object.values(hooks).forEach(hook => {
  router.beforeEach(hook)
})

4. 繪制頁面

    1. 登錄、注冊公共組件
// src/components/form-submit.vue
<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用戶名"
        placeholder="用戶名"
        :rules="[{ required: true, message: '請?zhí)顚懹脩裘? }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密碼"
        placeholder="密碼"
        :rules="[{ required: true, message: '請?zhí)顚懨艽a' }]"
      />
      <van-field
        v-if="isReg"
        v-model="repassword"
        type="password"
        name="repassword"
        label="重復密碼"
        placeholder="重復密碼"
        :rules="[{ required: true, message: '請?zhí)顚懨艽a' }]"
      />
      <div style="margin: 16px" v-if="isLogin">
        <van-button round block type="info" native-type="submit"
          >登錄</van-button
        >
        <br />
        <van-button round block to="/reg" type="primary">去注冊</van-button>
      </div>
      <div style="margin: 16px" v-if="isReg">
        <van-button round block native-type="submit" type="info"
          >注冊</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script >
export default {
  data() {
    return {
      username: "",
      password: "",
      repassword: "",
    };
  },
  computed: {
    isLogin() {
      return this.$route.path === "/login";
    },
    isReg() {
      return this.$route.path === "/reg";
    },
  },
  methods: {
    onSubmit(values) {
      this.$emit("submit", values);
    },
  },
};
</script>
    1. 個人中心
// src/views/profile/index.vue
<template>
  <div class="profile">
    <van-nav-bar title="個人中心"></van-nav-bar>
    <div class="profile-info">
      <template v-if="true">
        <img src="@/assets/logo.png" />
        <van-button size="small" to="/login">登錄</van-button>
      </template>
      <template v-else>
        <!-- 頭像上傳 -->
        <img src="@/assets/logo.png" />
        <span>張三</span>
      </template>
    </div>
  </div>
</template>
<style lang="scss">
.profile {
  .profile-info {
    display: flex;
    align-items: center;
    height: 150px;
    padding: 0 15px;
    img {
      width: 100px;
      height: 100px;
    }
  }
}
</style>
    1. 登錄頁面
// src/views/login/index.vue
<template>
  <div>
    <van-nav-bar
      title="登錄"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>
    <FormSubmit @submit="submit"></FormSubmit>
  </div>
</template>
<script >
import FormSubmit from "@/components/form-submit";

export default {
  components: {
    FormSubmit,
  },
  methods: {
    submit(values) {
      console.log(values);
    },
  },
};
</script>
    1. 注冊頁面
// src/views/reg/index.vue
<template>
  <div>
    <van-nav-bar
      title="注冊"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>
    <FormSubmit @submit="submit"></FormSubmit>
  </div>
</template>

<script >
import FormSubmit from "@/components/form-submit";
export default {
  components: {
    FormSubmit,
  },
  methods: {
    submit(values) {
      console.log(values);
    },
  },
};
</script>
    1. 路由配置
// src/router/index.js  新增下面路由
  {
    path: '/login',
    name: 'login',
    component: loadable(() => import('@/views/login/index.vue'))
  },
  {
    path: '/reg',
    name: 'reg',
    component: loadable(() => import('@/views/reg/index.vue'))
  }
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末媚朦,一起剝皮案震驚了整個濱河市氧敢,隨后出現的幾起案子,更是在濱河造成了極大的恐慌询张,老刑警劉巖孙乖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異份氧,居然都是意外死亡唯袄,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門蜗帜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恋拷,“玉大人,你說我怎么就攤上這事钮糖∶仿樱” “怎么了?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵店归,是天一觀的道長阎抒。 經常有香客問我,道長消痛,這世上最難降的妖魔是什么且叁? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮秩伞,結果婚禮上逞带,老公的妹妹穿的比我還像新娘。我一直安慰自己纱新,他們只是感情好展氓,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著脸爱,像睡著了一般遇汞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上簿废,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天空入,我揣著相機與錄音,去河邊找鬼族檬。 笑死歪赢,一個胖子當著我的面吹牛,可吹牛的內容都是我干的单料。 我是一名探鬼主播埋凯,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼点楼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了递鹉?” 一聲冷哼從身側響起盟步,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎躏结,沒想到半個月后却盘,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡媳拴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年黄橘,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片屈溉。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡塞关,死狀恐怖,靈堂內的尸體忽然破棺而出子巾,到底是詐尸還是另有隱情帆赢,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布线梗,位于F島的核電站椰于,受9級特大地震影響,放射性物質發(fā)生泄漏仪搔。R本人自食惡果不足惜瘾婿,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望烤咧。 院中可真熱鬧偏陪,春花似錦、人聲如沸煮嫌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽昌阿。三九已至饥脑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間宝泵,已是汗流浹背好啰。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工轩娶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留儿奶,地道東北人。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓鳄抒,卻偏偏與公主長得像闯捎,于是被迫代替她去往敵國和親椰弊。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內容

  • 前言 接觸vue框架也有一個多月的時間了瓤鼻,整理下之前做過的一個小demo秉版,主要是熟悉vue全家桶技術,界面布局模仿...
    視覺派Pie閱讀 26,551評論 20 285
  • 一茬祷、概念介紹 Vue.js和React.js分別是目前國內和國外最火的前端框架清焕,框架跟類庫/插件不同,框架是一套完...
    劉遠舟閱讀 1,061評論 0 0
  • 引言 記錄 vue 項目中所使用的技術細節(jié)祭犯,此文著重使用和封裝層面秸妥,原理性的東西會附上參考文章鏈接。 建議 clo...
    LM林慕閱讀 4,936評論 3 15
  • 在前端這個小圈子里充盈著各種各樣的技術撲沃粗,而且他們的更新速度快粥惧,讓我作為一個前端小白很難適應,最近恰好趕上公司要換...
    _花閱讀 8,302評論 4 10
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月最盅,有人笑有人哭突雪,有人歡樂有人憂愁,有人驚喜有人失落涡贱,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,536評論 28 53