美文网首页
开发之路十四——公众号H5开发(vue2+vant2)

开发之路十四——公众号H5开发(vue2+vant2)

作者: 林几许 | 来源:发表于2022-09-14 14:01 被阅读0次
    前言:记录项目的整个流程

    1、创建项目:vant框架(http://vant-ui.gitee.io/#/zhCN/quickstart

    按照vant官网的安装-创建项目流程:

    # 安装 Vue Cli
    npm install -g @vue/cli
    # 创建一个项目
    vue create hello-world
    # Vue 2 项目,安装 Vant 2
    npm i vant -S
    或
    npm i vant@latest-v2 -S
    

    2、添加依赖(持续更新)

    名称 用途 安装命令
    axios 请求 npm install axios
    vue-router 路由 npm install vue-router --save
    vuex 状态管理 npm install vuex --save
    less less 编译 npm install less less-loader --save
    lib-flexible 适配 npm i lib-flexible --save
    moment 日期处理 npm install moment --save

    3、目录结构

    层级 名称(部分自定义) 解释
    0 根目录 项目根目录
    0-1 node-modules npm install后生成的依赖
    0-2 public 打包时不会被编译,原封不动的放到dist下,相等于static,纯静态资源
    0-3 src: 主要资源文件,开发都在这个里面
    assets 资源目录
    api 存放接口的地方
    components 公共组件
    lib 存放vant组件引用,具体见后面详解
    router 路由
    store: vuex状态管理
    —modules 细分存放状态管理
    —index 整合所有状态管理-总管理页面
    utils: 工具
    —config 存放全局常量,如服务地址,appid等
    —httpServer 存放axios配置
    —tools 常用工具
    views 页面存放处
    App.vue 根组件
    main.js 入口js文件
    0-4 package.json 依赖版本控制
    0-5 readme.md 项目介绍
    0-6 vue.config.js vue配置,代理等

    4、代理(解决跨域问题)

     devServer:{
        proxy: {
          "/a": {
            target: "https://xxx.com.cn",
            changeOrigin: true, //是否跨域
            secure: false,
            pathRewrite: {
                '^/a': '/a' //重写接口
            },
            cookieDomainRewrite: ''
          }
        }
      }
    

    5、axios配置

    • 判断token
    //获取cookie
    const token = getCookie('access_token');
    
    • 添加token到request的header中
    if (token) {
          config.headers.Authorization = `Bearer ${token}`;
    }
    -----tools.js----
    function getCookie(str) {
      const name = `${str}=`;
      const ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i += 1) {
        const c = ca[i].trim();
         if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
      }
      return null;
    }
    
    • 更改返回状态码
    if (res.status == 200) {
          return res.data
    }
    

    6、vuex说明(https://vuex.vuejs.org/zh/guide/)

    • index.js
    //存放细分后的用户相关状态操作等
    export default new Vuex.Store({
      modules: {
        User,
        Login
      }
    })
    
    • 细分之后的单个store
    import UserApi from '@/api/User';
    const userApi = new UserApi();
    //存储的公共数据
    const state = {
      userInfo: localStorage.getItem('userInfo') ? localStorage.getItem('userInfo') : {}
    };
    //处理过的数据
    const getters = {
    };
    //唯一更改数据的方法
    const mutations = {
        SET_USER_INFO(state, data) {
        state.userInfo = data;
      }
    };
    //调用更改数据的方法,常用于请求后,调用mutations的方法去更改公共数据
    const actions = {
        async getUserInfo({ commit }) {
          const res = await userApi.getUser();
          if(res.result === 200){
            commit('SET_USER_INFO',res.data)
            localStorage.setItem('userInfo',res.data)
          }else{
            commit('SET_USER_INFO', {})
            localStorage.removeItem('userInfo')
          }
        }
    }
    
    export default {
      state,
      getters,
      mutations,
      actions,
    };
    
    • api接口
    import http from '@/utils/httpServer'
    import { BASE_URL } from '@/utils/config';
    
    export default class UserApi{
      //获取用户信息
      getUser() {
          return http.get(`${BASE_URL}/user`);
      }
    }
    

    7、vue-router路由(https://router.vuejs.org/zh/introduction.html)

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import Home from '../views/home.vue'
    
    Vue.use(VueRouter)
    
    const routes = [
      {
        path: '/',
        name: 'home',
        meta:{
          title:'顶部名称'
        },
        component: Home
      },
      {
        path: '/other',
        name: 'other',
        meta:{
          title:'顶部名称'
        },
        component: () => import('../views/other.vue')
      }
    ]
    
    const router = new VueRouter({
      routes
    })
    
    router.beforeEach((to,from,next)=>{
      //如果要用相同的名称,这里做判空显示默认
      document.title = to.meta && to.meta.title;
      next()
    })
    export default router
    

    8、Vant使用

    • npm引入后,在src目录下创建一个lib文件夹,里面创建一个vant.js
    import Vue from 'vue';
    import {
        Icon,
        Button
    } from 'vant'
    //按需引入
    Vue.use(Icon);
    Vue.use(Button);
    
    • 在main.js中引入vant.js,代码中即可使用vant组件
    import './lib/vant';
    

    相关文章

      网友评论

          本文标题:开发之路十四——公众号H5开发(vue2+vant2)

          本文链接:https://www.haomeiwen.com/subject/zhbkortx.html