Introduction to vue (vue-cli+vue-router)+babel+webpack project construction (3) Development practice

Introduction to vue (vue-cli+vue-router)+babel+webpack project construction <3>

This series of articles will introduce the construction process of the front-end project based on vue+webpack. The article is divided into four chapters. The first chapter introduces the deployment of the development environment, the second chapter introduces the construction of the project, the third chapter uses a pure front-end project with login-main interface as an example for actual development, and the fourth chapter introduces the project packaging and deployment And problems that may be encountered when deploying and going online. This series of articles mainly introduces the process of project construction. It aims to provide an introduction to the process for readers who do not understand the development process of modern front-end projects, and will not delve into some details. Therefore, this article is suitable for beginners to read. Please download
the supporting sample code used in this series of articles at the sample code download link . The actual combat project in this article can be browsed and watched at the project online address .
At the time of writing this series of articles, the version numbers of each framework plugin are as follows:

  • nodejs v10.4.1;
  • npm v6.1.0;
  • vue v2.5.2;
  • vue-cli v2.9.6;
  • vue-router v3.0.1;
  • vuex v3.1.0;
  • babel v6.5.2;
  • babel-polyfill v6.23.0;
  • webpack v3.6.0;

Development function - actual combat example

With the project successfully started, let's populate the project with some content. For the sample project "Dianke Forum" in this article, it has a login interface Login; there is a main interface Main, and there are two sub-interfaces in the main interface: a login log interface LogInfo and a forum content interface HomePage; finally there is a 404 interface NotFound . Now let's implement them. To understand the specific structure of the project, please check the online browsing address of the project .

Install plugin dependencies according to the project

When initializing the project, the scaffolding template of vue-cli has placed some plugin dependencies for the project. But sometimes in order to meet the needs of the project, it is necessary to continuously add plug-ins, and Dianke Forum is no exception. In this project we need to add two additional plugin dependencies, vuex and babel-polyfill . First modify the dependencies item in the package.json file and add two dependencies. The modified results are as follows:

"dependencies": {
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.1.0",
    "babel-polyfill": "^6.26.0"
  }

We added two plug-in dependencies, vuex v3.1.0 and babel-polyfill v6.26.0, to the project, where vuex provides state management services for the project, and babel-polyfill escapes some ES6 syntax that babel does not support by default. Because these two plugins are runtime plugins, they need to be placed in dependencies.

Plug-in version symbols
In package.json, you can specify the version numbers that dependencies and devDependencies plug-ins depend on. There are the following symbols:
1.version must be completely consistent with version, such as 1.2.2;
2.>version, >= version is greater than or greater than or equal to version;
3. <version, <=version is less than or less than or equal to version;
4. The minor version number of version is not lower than version. For example , 1.2.2 means that the latest version of 1.2.x is installed (not lower than 1.2.2), but 1.3.x is not installed, that is to say, the major version number and minor version number are not changed during installation; 5.^version
middle The version number is not lower than version. For example, ˆ1.2.2 means that the latest version of 1.xx (not lower than 1.2.2) is installed, but 2.xx is not installed, that is to say, the major version number is not changed during installation.
6.*all;
7.latest latest version;
Generally speaking, if the major version number (version number is divided into three digits: major version, medium version and minor version) of a plug-in (or framework) remains unchanged, its API and usage Is not going to change much. Therefore, under normal circumstances, the version number in package.json only needs to ensure that the major version number is the same.

Under the root directory path of the project (D:\WebStorm\workspace\dk-bbs), use cmd to execute the " npm install " command to install the two new plugins. After npm executes for a period of time, the plugin is downloaded and installed. At this time, restart the project, use cmd to execute " npm start " under the project root directory path (D:\WebStorm\workspace\dk-bbs) to start the project.
If you have started the project with cmd before, there are two simple ways to stop the running of the project:
1. Directly close the cmd command line window to stop the running project;
2. Use the ctrl+c shortcut key to terminate the current execution task, thus stopping the operation of the project;

Configuration code within the project

With the extra plugins installed, let's start actually developing the program. Write the configuration code first.

vue-router routing configuration

Dianke Forum This project includes 5 interface routes: login page, main page, two sub-pages under the main page, and 404 page. According to such a routing structure, we can write a vue-router page structure configuration. Find the vue-router configuration file. This configuration file already exists when vue-cli generates the project. Its directory location is: D:\WebStorm\workspace\dk-bbs\src\router\index.js. The modified code is as follows:

import Vue from 'vue'
import Router from 'vue-router'
import Login from "@/components/Login.vue";
import Main from "@/components/Main.vue";
import HomePage from "@/components/HomePage.vue";
import LogInfo from "@/components/LogInfo.vue";
import NotFound from "@/components/NotFound.vue";

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: "/",
      redirect:"/login"
    },
    {
      path:"/login",
      name:"Login",
      component:Login
    },
    {
      path: "/main",
      name: "Main",
      component: Main,
      children: [
        {
          path:"homepage",
          name:"HomePage",
          component:HomePage
        },
        {
          path:"loginfo",
          name:"LogInfo",
          component:LogInfo
        }
      ]
    },
    //404
    {
      path: '*',
      name:"NotFound",
      component:NotFound
    }
  ]
})

As you can see, because there are not many project modules, we put all the vue single files in the components directory. In actual product development, when there are too many project modules involved, all page files cannot be simply exposed under components, and file directories should be stored according to modules. Otherwise, it will cause maintenance difficulties that are inconvenient to read and find.
In the vue-router configuration file, first use importthe statement to introduce the dependencies of each module, then Vue.use(Router)load the plug-in through the method, and then export a Router object to control the routing relationship of the project.
The login page Login, the main interface Main page, and the 404 page are all outermost (the path of the 404 page is configured as "*", which means that as long as the previous routes are not matched successfully, the 404 page will be entered), The HomePage interface and the LogInfo interface exist as two subpages of the Main interface.
For the vue-router configuration file, developers need to pay attention. The path of the child route (children) cannot contain the "/" symbol. With the "/" symbol, it becomes an absolute path, which will cause the child route to fail. . For example, in this project, homepage is a sub-route, do not write it as path:”/homepage” , the correct way to write it is path:”homepage” , which is a rule of the vue-router plugin.

vuex state control configuration

In the Dianke Forum project, the data that needs to be shared among various modules include: recording user behavior and current user name. So we need to configure them into the vuex configuration file.
First of all, because vuex is an additional plug-in we introduced, the vue-cli scaffolding does not use it directly, and developers need to manually configure and use vuex. Create a new folder named "store" in the D:\WebStorm\workspace\dk-bbs\src\ directory, and create a new index.js file in the store folder. Add the following content to the index.js file:

import Vue from 'vue';
import Vuex from "vuex";

Vue.use(Vuex);
const store=new Vuex.Store({
  state: {
    username:"",
    logs:[]
  },
  mutations: {
    login:(state,data)=>{
      state.username=data;
    },
    pushLog:(state,data)=>{
      state.logs.push(data);
    }
  }
});

export default store;

It can be observed that vuex is very close to the style of vue-router configuration files. They all introduce dependencies first, use Vue.use(Vuex)to load plugins, and then export a configuration file. In the D:\WebStorm\workspace\dk-bbs\src\store\index.js file, we initialized two state quantities: username and logs. Respectively represent the global user name and the global user operation log. Then we define two triggers: login and pushLog to modify the state quantity.
After completing the configuration of vuex, the entire project needs to read this configuration file. Modify the D:\WebStorm\workspace\dk-bbs\src\main.js file. The content of the modified file is as follows:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

The modified content is: the vuex configuration file store\index.js is introduced and the store is deployed in new Vue().
After writing the configuration codes in the above projects, we can start the development of business codes.

Business code within the project

Login page Login

The login interface consists of an input box and a button. The input box is used to enter the user name, and the main interface will enter after pressing the button. The corresponding program will start logging user information.
The code for the login page is very simple, as follows:

<template>
  <div class="login-content">
    <form action="" onsubmit="return false">
      <input ref="username" type="text" name="username">
      <input type="submit" value="登录" v-on:click="login">
    </form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {};
  },
  methods:{
    login:function(){
      this.$router.push("main");
      this.$store.commit("login",this.$refs.username.value);
      this.$store.commit("pushLog",`用户:${this.$refs.username.value}在中国时间:${new Date()}登录系统`);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Main interfaceMain

There is a navigation bar at the head of the main interface, and the navigation bar will be routed to each page in the project. Events are bound to each navigation bar button to record user actions. The page code is as follows:

<template>
  <div class="main-content">
    <header class="header">
      <nav v-for="item in navs" v-on:click="toPage(item.url)">{
   
   {item.name}}</nav>
    </header>
    <div>
      <transition>
        <router-view></router-view>
      </transition>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Main',
  data () {
    return {
      navs:[
        {url:"login",name:"登录页"},
        {url:"homepage",name:"首页"},
        {url:"loginfo",name:"日志信息"},
        {url:"notfound",name:"404页面"}
      ]
    }
  },
  methods:{
    toPage:function(url){
      if(url==='login'){
        this.$router.push('/login');
      }else{
        this.$router.push(`/main/${url}`);
      }
      this.$store.commit("pushLog",`${this.$store.state.username}进入了${url}页面`);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .main-content .header{
    border-bottom:1px solid;
  }
</style>

The sub-interfaces HomePage and LogInfo of the main interface

The HomePage interface displays a text message of welcome to log in. code show as below:

<template>
  <div class="homepage-content">
    <p>{
   
   {msg+username}}</p>
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  data () {
    return {
      msg:"欢迎登录点客论坛,"
    }
  },
  computed:{
    username:function(){
      return this.$store.state.username;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

LogInfo obtains log information from the store object managed by vuex, and displays all logs. code show as below:

<template>
  <div class="loginfo-content">
    <ul>
      <li v-for="item in logs">{
   
   {item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'LogInfo',
  data () {
    return {};
  },
  computed:{
    logs:function(){
      return this.$store.state.logs;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

It can be observed from the codes of these two pages that when using the state stored in the store in the page, variables need to be placed in computed as the return value of the function to return. Only in this way can we ensure that every time a trigger (mutation) changes the value in the store, the page can listen to the change. Similarly, it is also possible to use watch .

404 interface NotFound

This interface displays a picture to remind the user that the current routing is wrong. Also provide a button to return to the home page. The images referenced by the page are placed in the path D:\WebStorm\workspace\dk-bbs\static\img. code show as below:

<template>
  <div class="notfound-content">
    <p v-on:click="toPage('homepage')">{
   
   {msg}}</p>
    <img v-bind:src="picUrl">
  </div>
</template>

<script>
export default {
  name: 'NotFound',
  data () {
    return {
      msg:"返回首页",
      picUrl:" /static/img/404.png"
    }
  },
  methods:{
    toPage:function(url){
      this.$router.push(`/main/${url}`);
      this.$store.commit("pushLog",`${this.$store.state.username}进入了${url}页面`);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Development summary

So far, we have completed the implementation of the entire project. The picture below is the "log information" page in Dianke Forum, which will record all the operation behaviors after entering the website.
insert image description here
Because the project started based on vue-cli+webpack has a hot reload mechanism, so after the developer modifies the project code, the change will automatically take effect in the page content. It can be seen that the project at this time has been running well in the development environment.
Although the content of this sample project is very simple, and the modules are very few (only five page routes), but I believe that this sample project has well demonstrated the role of each plug-in in the project under the single-page application built based on the Vue ecology and associations are shown. For beginners, we must carefully understand the role of each link in the project. For readers who need more in-depth study, the plug-in official website and plug-in source code provide developers with clearer instructions and explanations.

The front-end single-page application url hash value introduces
the anchor of the url ( the content after **#) instructs the browser which part of the page to display. Other common names for anchors are: bookmark or hash. Anchors always start with the #** symbol, such as http://localhost:8080/#/login.
The traditional use of anchors is for developers to make it easy for users to "jump" between sections of a long documentation page. For example, there is a table of contents at the top of the page, and all section headings link to their corresponding sections in the document. There may be a "back to top" link at the end of each chapter. Blogs and forums still use this mechanism extensively.
A unique feature of the anchor is that the browser does not reload the page when it changes. Anchors are therefore an ideal place to store application state, which is the most widely used technique for single-page applications. But at the same time, it should be noted that just because the change of the anchor will not cause the page to refresh, the single-page application will not refresh the scroll bar when switching pages.

Finally, let's briefly review what we have done in this chapter:
1. Introduce additional plugin dependencies, install them with npm install, and then restart the project;
2. To make the additionally introduced plugins usable, you need to add/modify Some configuration files and how to use the plug-in will be introduced in detail on the plug-in official website;
3. According to the needs of the project, write the vue-router routing configuration;
4. Write the business code;
5. If you need to introduce additional plug-ins during the development process, then Repeat steps 1-2. If a new routing structure needs to be added during the development process, repeat the 3 steps;

Guess you like

Origin blog.csdn.net/yuhk231/article/details/88613568