Vue development mobile terminal h5 environment construction

Technology selection

The company now needs to develop h5 on the mobile side, using the popular vue 2.0 for development, the scaffolding used is Vant2, the network access uses axios, the routing jump uses vue-router, and the development tool is vscode, as an Android development program I am not familiar with vue, but fortunately, I have set up the environment. I will record the most detailed tutorial on using axios in vue in
Vant 2
vue cli
vue vue via blog vue router

Environment build

import library

I have installed nodejs here, and configured the Taobao mirror

npm config set registry https://registry.npm.taobao.org

. These configurations are available online, you can check them yourself.
Vscode cannot directly create a project in the tool, you must first create an empty folder, and then open the folder through vscode.
Create a VueForBlog folder under the E:\vueProject folder, use vscode to open it (vscode can only open one project by default, if you want to open more than one, you can use ctrl+shift+n), click the toolbar terminal, create a new terminal, and officially start Create project
terminal input

npm i vant@latest-v2 -S

re-enter

npm install -g @vue/cli

The installation is complete
insert image description here
Open package.json to see the dependencies
insert image description here
Create a project

vue create first-vue

This seems to be unable to use hump. I just reported an error when I first started using firstVue. Generally, there will be options. I chose vue2. insert image description here
After the creation is completed, it will look like this
insert image description here
. Remember, you need to cd into the project later, otherwise you should create references outside the project and
use the same method to introduce axios and router. , and postcss-px-to-viewport, postcss-pxtorem, lib-flexible that vant needs to use

npm install [email protected]
npm install axios
npm i -S amfe-flexible
npm install postcss postcss-pxtorem --save-dev
npm install postcss-px-to-viewport --save-dev
npm install --save less-loader less

Configuration Environment

Configure the basic style of vant to facilitate the reference of vant components. Create theme.less under first\src\assets\style\, content

// Color Palette
@black: #000;
@white: #fff;
@gray-1: #f7f8fa;
@gray-2: #f2f3f5;
@gray-3: #ebedf0;
@gray-4: #dcdee0;
@gray-5: #c8c9cc;
@gray-6: #969799;
@gray-7: #646566;
@gray-8: #323233;
@red: #ee0a24;
@blue: #1989fa;
@orange: #ff976a;
@orange-dark: #ed6a0c;
@orange-light: #fffbe8;
@green: #07c160;

// Gradient Colors
@gradient-red: linear-gradient(to right, #ff6034, #ee0a24);
@gradient-orange: linear-gradient(to right, #ffd01e, #ff8917);

// Component Colors
@text-color: @gray-8;
@active-color: @gray-2;
@active-opacity: 0.7;
@disabled-opacity: 0.5;
@background-color: @gray-1;
@background-color-light: #fafafa;
@text-link-color: #576b95;

// Padding
@padding-base: 4px;
@padding-xs: @padding-base * 2;
@padding-sm: @padding-base * 3;
@padding-md: @padding-base * 4;
@padding-lg: @padding-base * 6;
@padding-xl: @padding-base * 8;

// Font
@font-size-xs: 10px;
@font-size-sm: 12px;
@font-size-md: 14px;
@font-size-lg: 16px;
@font-weight-bold: 500;
@line-height-xs: 14px;
@line-height-sm: 18px;
@line-height-md: 20px;
@line-height-lg: 22px;
@base-font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue',
  Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB',
  'Microsoft Yahei', sans-serif;
@price-integer-font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial,
  sans-serif;

// Animation
@animation-duration-base: 0.3s;
@animation-duration-fast: 0.2s;
@animation-timing-function-enter: ease-out;
@animation-timing-function-leave: ease-in;

// Border
@border-color: @gray-3;
@border-width-base: 1px;
@border-radius-sm: 2px;
@border-radius-md: 4px;
@border-radius-lg: 8px;
@border-radius-max: 999px;

In the same directory, create a public.css with the content


body {
    
    
  background-color: #f8f8f9;
  min-height: 100vh;
  min-width: 100vw;
}
.padding-lr10 {
    
    
  padding: 0 10px;
}
.phoneContant header .van-nav-bar {
    
    
  text-align: center;
  line-height: 56px;
  background: #68c2bd;
}
h3 {
    
    
  font-size: 16px;
}
.phoneContant header .van-nav-bar .van-icon {
    
    
  font-size: 20px;
  color: #fff;
}
.phoneContant header .van-nav-bar__title {
    
    
  color: #fff;
}
.contant {
    
    
  padding: 0 10px;
}
.re {
    
    
  position: relative;
}
.cardContant {
    
    
  background: #f5f5f5;
  height: 78vh;
  width: 100%;
  clear: both;
  padding: 8px 0;
}
.hosImg {
    
    
  width: 60px !important;
  height: 60px !important;
  border-radius: 50%;
}


The content here is customized according to the styles required in the project and configured
in vue.config.js

css: {
    
    
    loaderOptions: {
    
    
      less: {
    
    
        lessOptions: {
    
    
          modifyVars: {
    
    
            // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
            hack: `true; @import "@/assets/style/theme.less";`,
          },
        },
      },
    },
  },

There is a quick way to access the resource path. Set a symbol to directly specify the src directory, which is more convenient than using .or ..not easy to make mistakes. Also in vue.config.js, @it represents the src directory

  chainWebpack: (config) => {
    
    
    config.resolve.alias.set("@", resolve("src"));
    config.plugin("html").tap((args) => {
    
    
      args[0].minify = false;
      return args;
    });
  },

All content of vue.config.js

const path = require("path");
// const CompressionWebpackPlugin = require("compression-webpack-plugin");
// // 定义压缩文件类型
// const productionGzipExtensions = ["js", "css"];
// let timeStamp = new Date().getTime();

function resolve(dir) {
    
    
  return path.join(__dirname, dir);
}
module.exports = {
    
    
  // 基本路径
  publicPath: "./",
  // 输出文件目录 不写则默认根目录
  outputDir: "dist",
  assetsDir: "static", // 静态资源目录 (js, css, img, fonts)
  lintOnSave: false,
  // eslint-loader 是否在保存的时候检查
  // lintOnSave: 'error',
  // devServer: {
    
    
  //   // development server port 8000
  //   port: 8000,
  //   // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
  //   proxy: {
    
    
  //     '/api/': {
    
    
  //       target: process.env.VUE_APP_APIUrl,
  //       changeOrigin: true
  //     }
  //   }
  // },
  // /assets/style/public.css.less
  css: {
    
    
    loaderOptions: {
    
    
      less: {
    
    
        lessOptions: {
    
    
          modifyVars: {
    
    
            // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
            hack: `true; @import "@/assets/style/theme.less";`,
          },
        },
      },
    },
  },
  devServer: {
    
    
    // 设置主机地址
    // 设置默认端口
    port: 8080,
    // // 设置代理
    // proxy: {
    
    
    //   "/": {
    
    
    //     // target: "http://198.166.21.56:8080/",
    //     ws: true, // 支持ws协议;websocket的缩写;
    //     changeOrigin: true, // 是否跨域
    //     pathRewrite: {
    
    
    //       // 路径替换
    //       "^/api": "",
    //     },
    //   },
    // },
   
  },
  // use the full build with in-browser compiler?
  // https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
  // compiler: false,

  // webpack配置
  // see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md   webpack链接API,用于生成和修改webapck配置
  //部署打包html带引号
  chainWebpack: (config) => {
    
    
    config.resolve.alias.set("@", resolve("src"));
    config.plugin("html").tap((args) => {
    
    
      args[0].minify = false;
      return args;
    });
  },
  //压缩打包文件大小
  configureWebpack: (config) => {
    
    
    if (process.env.NODE_ENV === "Production") {
    
    
      // config.output.filename = `assets/js/[name].${timeStamp}.js`;
      // config.output.chunkFilename = `assets/js/[name].${timeStamp}.js`;
      config.plugins.push(
        new CompressionWebpackPlugin({
    
    
          algorithm: "gzip",
          test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"),
          threshold: 10240,
          minRatio: 0.8,
        })
      );
    }
    config.externals = {
    
    
      //   'vue': 'Vue',
      //   'vuex': 'Vuex',
      //   'vue-router': 'VueRouter',
      //   'element-ui': 'ELEMENT',
      //   'Axios': 'axios',
      //   'jquery': '$',
      //   'moment': 'moment',
      //   'js-cookie': 'Cookies',
      //   'echarts': 'echarts',
      //   'tinymce/tinymce': 'tinymce'
    };
    // }
  },
  // configureWebpack: (config) => {// webpack配置,值位对象时会合并配置,为方法时会改写配置
  //   if (debug) { // 开发环境配置
  //     config.devtool = 'cheap-module-eval-source-map'
  //   } else { // 生产环境配置

  //   }
  //   Object.assign(config, { // 开发生产共同配置
  //     resolve: {
    
    
  //       alias: {
    
    
  //         '@': path.resolve(__dirname, './src')//设置路径别名
  //         //...
  //       }
  //     }
  //   })
  // },
  // vue-loader 配置项
  // https://vue-loader.vuejs.org/en/options.html
  // vueLoader: {},

  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  // css相关配置 配置高于chainWebpack中关于css loader的配置
  // css: {
    
    
  //   // 是否使用css分离插件 ExtractTextPlugin
  //   extract: true,
  //   // 开启 CSS source maps?是否在构建样式地图,false将提高构建速度
  //   sourceMap: false,
  //   // css预设器配置项
  //   loaderOptions: {},
  //   // 启用 CSS modules for all css / pre-processor files.
  //   modules: false
  // },
  // use thread-loader for babel & TS in production build
  // enabled by default if the machine has more than 1 cores 构建时开启多进程处理babel编译
  //parallel: require('os').cpus().length > 1,
  // 是否启用dll
  // See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#dll-mode
  // dll: false,

  // PWA 插件相关配置
  // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
  //pwa: {},
  // webpack-dev-server 相关配置
  // devServer: {
    
    
  //   open: process.platform === 'darwin',
  //   host: '0.0.0.0',
  //   port: 8080,
  //   https: false,
  //   hotOnly: false,
  //   proxy: null, // 设置代理
  //   before: app => { }
  // },
  // 第三方插件配置
  pluginOptions: {
    
    
    // ...
  },
};

lintOnSave: false,This means to turn off grammar checking, otherwise there will be a lot of errors and it will not work.
In the first-vue directory, create a new .postcssrc.js and configure postcss in it

module.exports = {
    
    
  plugins: {
    
    
    //...
    autoprefixer: {
    
    
      browsers: ["Android >= 4.0", "iOS >= 7"],
    },
    "postcss-pxtorem": {
    
    
      rootValue: 37.5, //vant-UI的官方根字体大小是37.5
      propList: ["*"],
    },
  },
};

Bottom security zone adaptation
Configure the bottom security zone adaptation in the index.html file under the public directory

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta base="/" id="base" />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover,user-scalable=no"
    />

    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title>首页</title>
  </head>

  <body>

    <!-- 开启顶部安全区适配 -->
    <van-nav-bar safe-area-inset-top />
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <!-- 开启底部安全区适配 -->
    <van-number-keyboard safe-area-inset-bottom />
  </body>
</html>
<script>
  
</script>

Under the src directory, create a new router directory, create a new index.js below, and configure the router

import Vue from "vue";
//路由
import VueRouter from "vue-router";
import {
    
     asyncRouterMap } from "@/config/router.config";
Vue.use(VueRouter);
const routes = []
  const router = new VueRouter({
    
    
    routes: routes.concat(asyncRouterMap),
   
    mode: "hash",
  });
  
  export default router;

In the config directory of src, create a new router.config, which corresponds to the route and the corresponding page

export const asyncRouterMap = [
  {
    
    
    path: "/",
    component: () => import("@/components/Header.vue"),
    meta: {
    
     title: "首页" },
    // redirect: '/dashboard/workplace',
    redirect: "/home",
    children: [
      {
    
    
        path: "/home",
        name: "home",
        component: () => import("@/views/Home.vue"),
        hidden: true,
        meta: {
    
     title: "首页" },
      },
      {
    
    
        path: "/second",
        name: "second",
        component: () => import("@/views/Second.vue"),
        hidden: true,
        meta: {
    
     title: "第二页" },
      },
     
    ],
  },
  {
    
    
    path: "*",
    redirect: "/home",
    hidden: true,
  },
];

The specific page will be created later
to modify App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>

export default {
    
    
  name: 'App',

}
</script>

<style>
#app {
    
    
  height: 100%;
}
.el-header,
.el-footer {
    
    
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

body > .el-container {
    
    
  margin-bottom: 40px;
}
</style>

I now need to encapsulate a header component, because each page has a header navigation bar, so it is encapsulated into a component
In the components directory, create a new Header.vue

<template>
  <div class="phoneContant">
    <header>
  
      <van-nav-bar
        class="personheader"
        :fixed="true"
        :placeholder="true"
        :safe-area-inset-top="true"
        :title="$route.meta.title"
        left-text=""
        :left-arrow="true"
        @click-left="back"
      />
    </header>
        <router-view></router-view>
  </div>
</template>

<script>

var config = {
    
    
  isAndroid: /Android/i.test(navigator.userAgent), //判断是否为移动端
  isIos: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //判断是否为IOS
};

export default {
    
    
  name: "Headers",
  //import引入的组件需要注入到对象中才能使用
  components: {
    
    },
  data() {
    
    
    //这里存放数据
    return {
    
    
      title: "",
    };
  },
  //监听属性 类似于data概念
  computed: {
    
    },
  //监控data中的数据变化
  watch: {
    
    
    $route: {
    
    
      handler(newRouter, fromRouter) {
    
    
      
      },
      immediate: true,
    },
  },
  //方法集合
  methods: {
    
    
    back() {
    
    
    this.$router.go(-1);
    
      return false;
    },
  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
    
    
    let cont = window.history.length;
    console.log("window.history.length-----------------roomstep");
    console.log(cont);
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    
    
    
  },
  beforeCreate() {
    
    }, //生命周期 - 创建之前
  beforeMount() {
    
    }, //生命周期 - 挂载之前
  beforeUpdate() {
    
    }, //生命周期 - 更新之前
  updated() {
    
    }, //生命周期 - 更新之后
  beforeDestroy() {
    
    }, //生命周期 - 销毁之前
  destroyed() {
    
    
  
  }, //生命周期 - 销毁完成
  activated() {
    
    }, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>

Introduce vant and css styles, and other components in main.js

import Vue from 'vue'
import App from './App.vue'
import "@/assets/style/public.css";
import router from "@/router";
import Vant from "vant";
import "vant/lib/index.less";
import "@/assets/style/public.css";
Vue.config.productionTip = false
Vue.use(Vant);

new Vue({
    
    
  router,
  render: h => h(App),
}).$mount('#app')

Create a views folder under src, create two new vue, Home.vue and Second.vue, the content is very simple
Home.vue

<template>

  <div class="phoneContant">
    <van-button type="warning" @click="goToNext">进入下一页</van-button>
  </div>
</template>

<script>

export default {
    
    
  name: "Home",
  data() {
    
    
    return {
    
    
      msg: "我是首页",
    };
  },
  methods: {
    
    
    goToNext() {
    
    
      this.$router.push("/second");
    },

  },
};
</script>

<style>
</style>

Second.view


<template>
<div>
    {
    
    {
    
    msg}}
</div>
  
</template>

<script>
export default {
    
    
    data(){
    
    
        return{
    
    
            msg:"第二页"
        }
    }
}
</script>

<style>

</style>

run

command line input

npm run serve

If there is no problem, it will work. If you want to interrupt the operation, use the ctrl+c shortcut key in the terminal
insert image description here

network encapsulation

Package axios for easy use. Create a new utils folder under src, create a new request.js under utils,

import axios from "axios";
import {
    
     Notify } from "vant";
import router from "@/router";

const baseURL =BaseUrl
  // process.env.NODE_ENV === "development" ? "/api" : window.productionUrl;
//创建axios实例
const service = axios.create({
    
    
  baseURL, // api的base_url  window.productionUrl
  withCredentials: true,
  timeout: 30000, // 请求超时时间
});

// 发送请求拦截器
service.interceptors.request.use(
  (config) => {
    
    
    const Nonce =
      Math.ceil(+new Date() / 1000) + "" + Math.ceil(Math.random() * 10000);
    const CurTime = Math.floor(+new Date() / 1000).toString();
    config.headers["Content-Type"] = "application/json;charset=UTF-8";

    return config;
  },
  (error) => {
    
    
    return Promise.reject(error);
  }
);

//发送请求响应拦截
service.interceptors.response.use(
  (response) => {
    
    
    const res = JSON.parse(CryptoJS.decrypt(response.data));
    // 错误的status情况
    // console.log(res);
    if (!res.result) {
    
    
      Notify({
    
     type: "danger", message: res.message || "error" });
      return Promise.reject(res.message || "error");
    } else {
    
    
      return res;
    }
  },
  (error) => {
    
    
    Notify({
    
     type: "danger", message: error.message || "error" });
    return Promise.reject(error);
  }
);

export default service;

epilogue

Now the project is just built. If there are no missing steps, it should be able to run. There is still a lot of work to do. . .

Replenish

The order of the previous project creation method should be wrong. It is not to create a folder first, then open it with vscode, and then execute the vue create command. In this case, there will be a subdirectory under the main directory, and the subdirectory is the project name. If you want the main directory to be the project, you need to create the project now, open the cmd command line, execute the command, and then open it with vscode
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/jifashihan/article/details/124659000