Vue 개발 모바일단말기 h5 환경 구축

기술 선택

회사는 이제 개발을 위해 인기 있는 vue 2.0을 사용하여 모바일 측면에서 h5를 개발해야 합니다. 사용된 스캐폴딩은 Vant2이고, 네트워크 액세스는 axios를 사용하고, 라우팅 점프는 vue-router를 사용하고, 개발 도구는 vscode를 Android로 사용합니다. 개발 프로그램 vue에 익숙하지 않은데 다행이 환경설정은 해놨네요 vue 에서 axios in vue를
Vant 2
vue cli
vue vue 블로그 vue 라우터를 통해
사용하는 가장 자세한 튜토리얼을 녹화하겠습니다.

환경 빌드

라이브러리 가져오기

여기에 nodejs를 설치하고 Taobao 미러를 구성했습니다.

npm 구성 설정 레지스트리 https://registry.npm.taobao.org

. 이러한 구성은 온라인에서 사용할 수 있으며 직접 확인할 수 있습니다.
Vscode는 도구에서 직접 프로젝트를 생성할 수 없으므로 먼저 빈 폴더를 생성한 다음 vscode를 통해 폴더를 열어야 합니다.
E:\vueProject 폴더 아래에 VueForBlog 폴더를 만들고 vscode를 사용하여 엽니다(vscode는 기본적으로 하나의 프로젝트만 열 수 있으며 둘 이상을 열려면 ctrl+shift+n을 사용할 수 있습니다). 툴바 터미널을 클릭합니다. , 새 터미널을 생성하고 공식적으로 프로젝트
터미널 생성을 시작합니다 입력

npm i vant@latest-v2 -S

재입장

npm 설치 -g @vue/cli

설치가 완료되었습니다.
여기에 이미지 설명 삽입
package.json을 열어 종속성을 확인하세요.
여기에 이미지 설명 삽입
프로젝트 생성

vue 생성 첫 번째 vue

이것은 hump를 사용할 수 없는 것 같습니다. 처음으로 firstVue를 사용하기 시작했을 때 방금 오류를 보고했습니다. 일반적으로 옵션이 나타납니다. vue2를 선택했습니다. 여기에 이미지 설명 삽입
생성이 완료되면 다음과 같이 표시됩니다
여기에 이미지 설명 삽입
. 나중에 프로젝트에 cd해야 합니다. 그렇지 않으면 프로젝트 외부에 참조를 만들고
동일한 방법을 사용하여 axios를 도입합니다. 및 router. 및 vant가 사용해야 하는 postcss-px-to-viewport, postcss-pxtorem, lib-flexible

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 -로더 적음

구성 환경

Vant 구성 요소를 쉽게 참조할 수 있도록 Vant의 기본 스타일을 구성합니다. first\src\assets\style\, content 아래에 theme.less 생성

// 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;

동일한 디렉토리에서 내용이 포함된 public.css를 생성합니다.


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%;
}


여기에 있는 콘텐츠는 프로젝트에 필요한 스타일에 따라 사용자 지정되고
vue.config.js에 구성됩니다.

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

리소스 경로에 빠르게 접근할 수 있는 방법이 있습니다 src 디렉토리에 직접 지정하는 심볼을 설정하면 사용하는 것보다 편리하거나 .실수 ..하기 쉽지 않습니다.또한 vue.config.js에서도 @src 디렉토리를 나타냅니다.

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

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,이것은 문법 검사를 끄는 것을 의미하며, 그렇지 않으면 많은 오류가 발생하고 작동하지 않습니다
.

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

하단 보안 영역 적응
공용 디렉터리 아래의 index.html 파일에서 하단 보안 영역 적응을 구성합니다.

<!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>

src 디렉터리 아래에 새 라우터 디렉터리를 만들고 아래에 새 index.js를 만들고 라우터를 구성합니다.

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;

src의 config 디렉토리에서 경로와 해당 페이지에 해당하는 새 router.config를 만듭니다.

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,
  },
];


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>

이제 헤더 구성 요소를 캡슐화해야 합니다. 각 페이지에는 헤더 탐색 모음이 있으므로 구성 요소로 캡슐화되므로
구성 요소 디렉토리에서 새 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>

vant 및 css 스타일과 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')

src 아래에 views 폴더를 만들고 두 개의 새로운 vue, Home.vue 및 Second.vue를 만듭니다. 내용은 매우 간단합니다.
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>

두 번째 보기


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

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

<style>

</style>

달리다

명령줄 입력

npm 실행 서브

문제가 없으면 작동합니다. 작업을 중단하려면 터미널에서 ctrl+c 단축키를 사용하십시오.
여기에 이미지 설명 삽입

네트워크 캡슐화

쉬운 사용을 위한 패키지 axios. src 아래에 새 utils 폴더를 만들고 utils 아래에 새 request.js를 만듭니다.

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;

발문

이제 프로젝트가 막 빌드되었습니다. 빠진 단계가 없으면 실행할 수 있어야 합니다. 아직 할 일이 많이 있습니다. . .

다시 채우다

이전 프로젝트 생성 방법의 순서가 틀려야 하는데 폴더를 먼저 생성한 후 vscode로 열어서 vue create 명령어를 실행하는 것이 아니라 메인 디렉터리 아래에 하위 디렉터리가 생기고, 하위 디렉토리는 프로젝트 이름입니다. 기본 디렉터리를 프로젝트로 사용하려면 지금 프로젝트를 만들고 cmd 명령줄을 열고 명령을 실행한 다음 vscode로 열어야 합니다.
여기에 이미지 설명 삽입
여기에 이미지 설명 삽입
여기에 이미지 설명 삽입

추천

출처blog.csdn.net/jifashihan/article/details/124659000