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中, 页面切换的时候,组件销毁的时候执行
        // 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 状态
        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方法来进行请求操作
    // 每次请求可以创建一个新的实例,如果业务不复杂,可以不创建实例,直接使用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去更改状态
  }
}

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) {  // 修改分类状态
    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中的状态绑定到当前的实例
    currentCategory: {
      get() {
        // 取值
        return this.category;
      },
      set(value) {
        // 修改状态,默认会调用mutation更改状态
        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. 定义公共的状态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: {  // 公共的状态
    tokens: []
  },
  mutations: {
    [Types.SET_TOKEN](state, token) {
      // 我们希望状态可以被追踪
      state.tokens = [...state.tokens, token]  // 存储token,页面切换可以让token依次执行
    },
    [Types.CLEAR_TOKEN](state) {
      state.tokens.forEach(token => token())  // 执行所有的取消方法,都调用一下
      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中, 页面切换的时候,组件销毁的时候执行
        // 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: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-if="isReg"
        v-model="repassword"
        type="password"
        name="repassword"
        label="重复密码"
        placeholder="重复密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <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,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容

  • 前言 接触vue框架也有一个多月的时间了,整理下之前做过的一个小demo,主要是熟悉vue全家桶技术,界面布局模仿...
    视觉派Pie阅读 26,551评论 20 285
  • 一、概念介绍 Vue.js和React.js分别是目前国内和国外最火的前端框架,框架跟类库/插件不同,框架是一套完...
    刘远舟阅读 1,061评论 0 0
  • 引言 记录 vue 项目中所使用的技术细节,此文着重使用和封装层面,原理性的东西会附上参考文章链接。 建议 clo...
    LM林慕阅读 4,933评论 3 15
  • 在前端这个小圈子里充盈着各种各样的技术扑,而且他们的更新速度快,让我作为一个前端小白很难适应,最近恰好赶上公司要换...
    _花阅读 8,302评论 4 10
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,536评论 28 53