preface

This article is suitable for vUE beginners, through VUE-CLI to quickly create vUE project, based on vant UI framework H5 simple framework. Compatible with mainstream mobile browsers. The content may be some not rigorous or understanding wrong place, welcome to put forward correction.

Through this paper, the following objectives can be roughly achieved:

  • Create a VUE project through VUe-CLI
  • Sass configuration
  • Secondary encapsulation of Axios
  • Vue-router is easy to use
  • Vuex is simple to use
  • Simple application of Vant
  • post-css-to-viewportMobile adaptation (Compatible with Vant)
  • Token Settings for login
  • Permission to design

Before reading, you’d better read the following official documents for quick comprehension:

  • Vue website

  • Vue – cli’s official website

  • Vue-router Official document

  • Vuex official document

  • Vant official documentation

  • Axios Chinese website

Create a project

Install vuE-CLI and create the project

# install Vue Cli NPM install -g@vue/Cli # Create a project Vue create vue-ant -demo # run a project CD vue-ant -demo NPM run serveCopy the code

The service launches the browser to visit the http://localhost:8080/ preview page

A simple VUE project has been built, and then it can be built on as needed.

SASS precompile processing

You can select a preprocessor (Sass/Less/Stylus) when creating your project. If not, the built-in WebPack will still be pre-configured to do all the processing. You can also install the corresponding WebPack loader manually:

Sass NPM install -d Sass -loader node-sassCopy the code

Installing Node-sass has a high failure rate, so keep your fingers crossed after executing the command

Sass-loader Node-sass After the two packages are installed successfully, you can directly write CSS using sass in the page without any configuration

Let’s test it out:

Modify app. vue file to remove automatically generated content, plus test code

<template> <div id="app"> <div class="test"> Sass </div> </div> </template> <style lang=" SCSS "scoped> #app {width: 100%; height: 30px; .test { color: red; font-size: 14px; } } </style>Copy the code

Note: The style tag requires the lang field to specify the precompiled language; The scoped field indicates that the current style applies only to the current page (component), with unique attributes (such as data-V-7ba5bd90) added at compile time

Let’s write the simplest sass nested syntax, and look at the page effect. The text has turned red, indicating that SASS is in effect. You can use it freely.

Vue – the router routing

Installation and Configuration

Vue Router is the official route manager of vue.js. (For details, please read vue-Router’s official website)

First installation

# install vue-router NPM install -s vue-routerCopy the code

Create a new views directory under the SRC directory to store the page. Let’s create two new page login and list page templates.

Add a router directory under the SRC directory to manage routes.

The specific directory structure is as follows:

src
  --views
    --login
      Index.vue
    --list
      Index.vue
  --router
    index.js
Copy the code

Write a few words to distinguish between the login page and the list page. Next, let’s configure the route

/src/router/index.js

Import Vue from 'Vue' import VueRouter from 'vue-router' import Login from '@/views/ Login/index.vue ' Import List from '@/views/ List/index.vue '// Some plugins (such as vue-router) automatically call vue.use () when they detect that vue is an accessible global variable. However, in a module environment like CommonJS, you should always explicitly call vue.use () vue.use (VueRouter) const routes = [{path: '/login', name: 'Login', component: Login, // meta meta: {title: "Login"}}, {path: '/list', name: 'list', component: List, meta: {title: "router"}},] const router = new VueRouter({// routes }) export default routerCopy the code

/scr/main.js

import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false new Vue ({/ / registered routing the router, render: h = > h (App),}). $mount (' # App)Copy the code

Does that give us routing access?

The login page is not displayed and no error is reported.

It turns out that we’re missing an important step that we need to show here in the component that adds router-view route matching

/src/App.vue

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

At this point access to http://localhost:8080/#/login http://localhost:8080/#/list can be properly accessed

Customize the page Title

Consider: Now that the title of the login and list pages is the default project name, how can I change it to a custom title?

/src/views/login/Index.vue

<script> export default {mounted(){document.title = '/ /script>Copy the code

After the page is loaded, change the title of the page. This will solve the problem, but it will be troublesome to add this operation to every page. Remember when we did the route configuration we added a meta property with the title field in it. We can solve this problem by using the global front-guard

/src/main.js

BeforeEach ((to, from, next) => {if(to.meta. Title){document.title = to.meta. Title} next()})Copy the code

The meta field is the routing meta field. Console. log(to) can see that we can get the configured title information from to.meta or to.matched array. This allows you to add a custom title to each page.

Introduce mobile UI framework Vant

Vant is a lightweight mobile UI component library developed by the Uzan team.

The installation

NPM install vant -sCopy the code

configuration

We chose to introduce all the components at once. You can refer to the official documentation for on-demand import

Register vant in main.js

import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
Copy the code

On the login page we introduce the button component to see what it looks like

/views/login/Index.vue

<div> <van-button type="primary"> </van-button> <div> </template>Copy the code

Vant already works, however, we see that the Vant style, in pixels, does not work with phones of different resolutions.

Vant adaptation

Vant’s official documentation provides Rem adaptation methods. For details, please refer to the official documentation

Rem also has to do px-> REM calculation, a bit of trouble. We use viewPort to solve the adaptation problem.

Postcss-px-to-viewport is a postCSS plugin that converts PX units to viewport units (vw, vh, vmin, vmax).

The installation

Install postcss-px-to-viewport -d NPM install postcss-px-to-viewport -dCopy the code

configuration

We need to add the.postcsrc. Js file in the root directory

The configuration is as follows:

const path = require('path'); module.exports = ({ file })=> { const designWidth = file.dirname.includes(path.join('node_modules', 'vant')) ? 375-750; Return {plugins: {autoprefixer: {}, // used to automatically add prefixes to different browsers such as -webkit-, -moz-, etc. "postcss-px-to-viewport": {unitToConvert: {plugins: {autoprefixer: {}, // used to automatically add prefixes to different browsers such as -webkit-, -moz-, etc. "postcss-px-to-viewport": {unitToConvert: ViewportWidth: designWidth, unitPrecision: 6, propList: ViewportUnit: "vw", // Specify the window unit to convert to, default vw fontViewportUnit: "Vw ", // specify the window unit to convert the font to, default vw selectorBlackList: ["wrap"], // specify the class name not to convert to the window unit, minPixelValue: MediaQuery: true, false replace: true, false replace: true, // exclude: [/node_modules/], // set ignore files, use re as the directory name to match landscape: false // whether to handle landscape}}}};Copy the code

The comments for the configuration items above are clear, just follow the instructions. Since vant px also needs to be converted to VW, exclude can no longer be configured to node_modules or to mismatch the Vant via regex

In addition, the viewportWidth attribute needs to set the width of the UI design draft. Vant is designed according to the design draft of 375, while we usually develop the design draft of 750, so this value needs to be determined.

Webpack plugins can configure objects as well as a function that can be called with two parameters, an environment object (ENV) and a Map object. This object describes the option passed to Webpack, from which output-filename can be taken to determine if it is Vant and thus assign a different value to vant.

Finally we restart the service to see if our style has been converted to VW:

Note that the postcss-px-to-viewPort plugin does not convert inline styles, so try to write styles outside the chain or inside the style

To be continued

This article will start here, these are the most basic applications, the basic related website has more detailed documentation. Or suggest to read more official documents, less detours.

Next update:

  • Vant implements login page, list page
  • Secondary encapsulation of Axios
  • The mock data
  • Interface cross – domain, proxy
  • Role/Permission Settings

Reference documentation

  • Postcss-px-to-viewport for mobile layout (compatible with Vant)
  • vue-element-admin
  • Vue family bucket + Vant mobile solution out of the box
  • Webpack has many configuration types