Create a project

Be careful : The command line should be run in administrator mode
1、 Create a file called hello-vue The engineering of vue init webpack hello-vue
2、 Installation dependency , We need to install vue-router、element-ui、sass-loader and node-sass Four plug-ins

# Enter the project directory cd hello-vue# install vue-routern cnpm install vue-router --save-dev# install element-uicnpm i element-ui -S# Installation dependency cnpm install#  install SASS loader cnpm install sass-loader node-sass --save-dev# Start test npm run dev

3、Npm Command interpretation :

  • npm install moduleName: Install the module to the project directory
  • npm install -g moduleName:-g It means to install the module to the global , The specific location of the disk depends on npm config prefix The location of
  • npm install -save moduleName:–save Install the module into the project directory , And in package Of documents dependencies Node write dependency ,-S Is the abbreviation of the command
  • npm install -save-dev moduleName:–save-dev Install the module into the project directory , And in package Of documents devDependencies Node write dependency ,-D Is the abbreviation of the command

Create a landing page

Delete the useless things !
   Create the following structure in the source directory :

  • assets: For storing resource files
  • components: To hold Vue Functional components
  • views: To hold Vue View component
  • router: To hold vue-router To configure

 Insert picture description here

Create the home page view , stay views Create a directory called Main.vue View component of :

<template><div> home page </div></template><script>export default {
		name:"Main"}</script><style scoped></style>

Create the login page view in views Create a directory named Login.vue View component of , among el-form The element of is ElementUI Components ;

<template>
  <div><el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">  <h3 class="login-title"> Welcome to login </h3>  <el-form-item label=" account number " prop="username"><el-input type="text" placeholder=" Please enter your account number " v-model="form.username"/>  </el-form-item>  <el-form-item label=" password " prop="password"><el-input type="password" placeholder=" Please input a password " v-model="form.password"/>  </el-form-item>  <el-form-item><el-button type="primary" v-on:click="onSubmit('loginForm')"> Sign in </el-button>  </el-form-item></el-form><el-dialog  title=" reminder "  :visible.sync="dialogVisible"  width="30%">  <span> Please enter your account number and password </span>  <span slot="footer" class="dialog-footer"><el-button type="primary" @click="dialogVisible = false"> indeed   set </el-button>  </span></el-dialog>
  </div></template><script>
  export default {name: "Login",data() {  return {form: {  username: '',  password: ''},//  Form validation , Need to be in  el-form-item  Add... To the element  prop  attribute rules: {  username: [{required: true, message: ' Account number cannot be empty ', trigger: 'blur'}  ],  password: [{required: true, message: ' The password cannot be empty ', trigger: 'blur'}  ]},//  Dialog shows and hides dialogVisible: false  }},methods: {  onSubmit(formName) {//  Bind validation to the form this.$refs[formName].validate((valid) => {  if (valid) {//  Use  vue-router  Route to the specified page , This is called programmed navigation this.$router.push("/main");  } else {this.dialogVisible = true;return false;  }});  }}
  }</script><style lang="scss" scoped>
  .login-box {border: 1px solid #DCDFE6;width: 350px;margin: 180px auto;padding: 35px 35px 15px 35px;border-radius: 5px;-webkit-border-radius: 5px;-moz-border-radius: 5px;box-shadow: 0 0 25px #909399;
  }

  .login-title {text-align: center;margin: 0 auto 40px auto;color: #303133;
  }</style>

Create route , stay router Create a directory called index.js Of vue-router Routing configuration file

import Vue from 'vue'import VueRouter from 'vue-router'import Main from '../views/Main'import Login from '../views/Login'Vue.use(VueRouter);export default new VueRouter({
  routes:[{  path: '/main',  name:'main',  component:Main},{  path:'/login',  name:'login',  component: Login}
  ]});

APP.vue

<template>
  <div id="app"><router-view></router-view>
  </div></template><script>export default {
  name: 'App',}</script><style>#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;}</style>

main.js

// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from './App'import router from "./router"import ElementUI from 'element-ui'import 'element-ui/lib/theme-chalk/index.css'Vue.use(ElementUI)/* eslint-disable no-new */new Vue({
  el: '#app',
  router,
  render:h=>h(App)})

Run the project

  1. Enter the command

    npm run dev
  2. If the error is reported, as shown in the figure below :Module build failed: TypeError: loaderContext.getResolve is not a function(sass-loader Version too high )

     Insert picture description here

    Or as shown in the figure below :Module build failed: TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received undefined

     Insert picture description here

    solve :

  • npm perform

    npm install node-sass --save-dev
  • npm Error report in execution , be cnpm perform

    cnpm install node-sass --save
         
  • If cnpm No installation

    npm install -g cnpm --registry=https://registry.npm.taobao.org
    
    // perhaps npm install -g cnpm
  1. Modify the configuration file , reinstall

    //1. modify sass-loader The version is ^7.3.1
    //2. Re install the configuration environment 
    npm install
    // perhaps 
    cnpm install

     Insert picture description here

  2. Uninstall current , Re Download

    //  Uninstall the current version npm uninstall sass-loader
    //  install 7.3.1 edition npm install sass-loader@7.3.1 --save-dev
  3. If the error is reported as :Module build failed: Error: Cannot find module ‘node-sass’

     Insert picture description here

Once again, it was successful

npm run dev

 Insert picture description here

 Insert picture description here

Route nesting

Nested routes are also called sub routes , in application , It is usually composed of multiple nested components . similarly ,URL The dynamic path of each segment in also corresponds to the nested components of each layer according to a certain structure , for example :

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+| User             |                  | User            || +--------------+ |                  | +-------------+ || | Profile      | |  +------------>  | | Posts       | || |              | |                  | |             | || +--------------+ |                  | +-------------+ |+------------------+                  +-----------------+

  1. User information components , stay views/user Create a directory called Profile.vue View component of ;

    <template>
        <div>
          <h1> Personal information </h1>
        </div>
    </template>
    
    <script>
        export default {
            name: "UserProfile"
        }
    </script>
    
    <style scoped>
    
    </style>
  2. The user list component is in views/user Create a directory called List.vue View component of ;

    <template>
        <div>
          <h1> User list </h1>
        </div>
    </template>
    
    <script>
        export default {
            name: "UserList"
        }
    </script>
    
    <style scoped>
    
    </style>
  3. Configure nested route modification router In the catalog index.js Routing configuration file , Code such as

    import Vue from 'vue'import Router from 'vue-router'import Main from '../views/Main'import Login from '../views/Login'import UserList from '../views/user/List'import UserProfile from '../views/user/proFile'Vue.use(Router);export default new Router({
      routes: [{  path: '/login',  component: Login},{  path: '/main',  component: Main,  children: [{  path: '/user/profile',  component: UserProfile},{  path: '/user/list',  component: UserList}  ]}
      ]})
  4. Modify the home page view , We modify Main.vue View component , Here we use ElementUI Layout container components , The code is as follows :

    <template>
        <div>
          <el-container>
            <el-aside width="200px">
              <el-menu :default-openeds="['1']">
                <el-submenu index="1">
                  <template slot="title"><i class="el-icon-caret-right"></i> User management </template>
                  <el-menu-item-group>
                    <el-menu-item index="1-1">
                      <router-link to="/user/profile"> Personal information </router-link>
                    </el-menu-item>
                    <el-menu-item index="1-2">
                      <router-link to="/user/list"> User list </router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
                <el-submenu index="2">
                  <template slot="title"><i class="el-icon-caret-right"></i> Content management </template>
                  <el-menu-item-group>
                    <el-menu-item index="2-1"> Classification management </el-menu-item>
                    <el-menu-item index="2-2"> The content list </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
              </el-menu>
            </el-aside>
    
            <el-container>
              <el-header style="text-align: right; font-size: 12px">
                <el-dropdown>
                  <i class="el-icon-setting" style="margin-right: 15px"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item> Personal information </el-dropdown-item>
                    <el-dropdown-item> Log out </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-header>
    
              <el-main>
                <router-view />
              </el-main>
            </el-container>
          </el-container>
        </div>
    </template>
    
    <script>
        export default {
            name: "Main"
        }
    </script>
    
    <style scoped lang="scss">
      .el-header {
        background-color: #B3C0D1;
        color: #333;
        line-height: 60px;
      }
    
      .el-aside {
        color: #333;
      }
    </style>

    explain :

    The element is configured to show nested routes , It mainly uses personal information to display nested routing content

Parameter passing

We often need to match a pattern to all the routes , All mapped to the same component . for example , We have a User Components , For all ID Different users , Use this component to render . At this point, we need to pass parameters ;

Component forwarding

$route The way

  1. Modify routing configuration ,

  • Mainly in the path Attribute added :id,:name Such placeholders

    import Vue from "vue";import VueRouter from "vue-router";import Main from '../views/Main';import Login from '../views/Login';import UserProfile from '../views/user/Profile';import UserList from '../views/user/List';Vue.use(VueRouter);export default new VueRouter({
      routes:[{  path: '/main',  component:Main,// Nested Route   children:[{ path:'/user/profile/:id',  name:'UserProfile',  component:UserProfile},{ path:'/user/list',  name:'UserList',  component:UserList}  ]},{  path: '/login',  component:Login}
      ]})

Pass parameters

  • At this point we are going to to Change it to :to, To use this property as an object ,

  • Be careful router-link Medium name The attribute name must be the same as... In the route name The attribute name matching , Because of this Vue To find the corresponding routing path ;

    <!--name: Pass the component name , params: Pass parameters ,  Object required : v-bind-->
    <router-link :to="{name:'UserProfile',params:{id:1}}"> Personal information </router-link>

Receiving parameters , In the target component

<div>
    <h1> Personal information </h1>
    {{$route.params.id}}
</div>

Use props The way

  1. Modify routing configuration , Mainly increased props: true attribute

    routes: [{  path: '/login',  component: Login},{  path: '/main',  component: Main,  children: [{  path: '/user/profile/:id/',  name: 'UserProfile',  component: UserProfile,  props: true},{  path: '/user/list',  component: UserList}  ]}
      ]
  2. Pass parameters as before

  3. Receive parameters to add... To the target component props attribute

    <template>
      <div>
        <h1> Personal information </h1>
        {{id}}
      </div>
    
    </template>
    
    <script>
    export default {
      props:['id'],
      name: "UserProfile"
    }
    </script>
    
    <style scoped>
    
    </style>

Component redirection

  • We all know the meaning of redirection , but Vue Redirection in is used when the paths are different but the components are the same , such as :

    {path: '/goHome',redirect: '/main'}
  • explain : There are two paths defined here , One is /main , One is /goHome

    • among /goHome Redirected to /main route , As you can see, redirection doesn't need to define components ;
  • Use the words , Just set the corresponding path ;

    <el-menu-item index="1-3">
        <router-link to="/goHome"> Back to the front page </router-link>
    </el-menu-item>

Routing mode and 404

There are two routing modes

  • hash: Path belt # Symbol , Such as http://localhost/#/login

    • The default is hash Routing mode

      export default new Router({
        routes: []})
  • history: The path does not take # Symbol , Such as http://localhost/login

    • history Routing mode

      export default new Router({
        mode: 'history',
        routes: []})

404

  1. Create a file called NotFound.vue View component of , The code is as follows :

    <template>
        <div>
          <h1>404, Your page is lost </h1>
        </div>
    </template>
    
    <script>
        export default {
            name: "NotFound"
        }
    </script>
    
    <style scoped>
    
    </style>
  2. Modify routing configuration , The code is as follows :

    import NotFound from '../views/NotFound'export default new Router({
      mode: 'history',
      routes: [{   path: '*',   component: NotFound}
      ]})

Routing hooks and asynchronous requests

Routing hook

  • beforeRouteEnter: Execute before entering the route

  • beforeRouteLeave: Execute before leaving the route

    export default {  name: "UserProFile",  props: ['id'],  beforeRouteEnter: (to,from,next) => {console.log(' Before entering the route ')next()  },  beforeRouteLeave: (to,from,next) => {console.log(' After leaving the route ')next()  }}

Parameter description :

  • to: Route information about the route to jump
  • from: Path information before path jump
  • next: Routing control parameters
  • next() Jump to the next page
  • next(’/path’) Change the jump direction of the route , Make it jump to another route
  • next(false) Return to the original page
  • next((vm)=>{}) Only in beforeRouteEnter Available in the ,vm Is a component instance

Asynchronous requests

  1. install Axios cnpm install --save axios

  2. main.js quote Axios

    import axios from 'axios'Vue.prototype.axios=axios;
  3. Prepare the data : Only ours static The files in the directory can be accessed , So we put the static files in this directory static/mock/data.json.

    {
      "name": "The_Beacon",
      "url": "https://blog.csdn.net/The_Beacon",
      "page": 1,
      "isNonProfit": true,
      "address": {"street": " Jinshi Road ","city": " Dalian, Liaoning ","country": " China "
      },
      "links": [{  "name": "BiliBili",  "url": "https://space.bilibili.com/300623241"},{  "name": "CSDN",  "url": "https://blog.csdn.net/The_Beacon"},{  "name": " Baidu ",  "url": "https://www.baidu.com/"}
      ]}
  4. Run the project npm run dev See if it works

  • because cnpm Installation may fail , Install it again cnpm install --save axios

 Insert picture description here

  1. stay beforeRouteEnter Make asynchronous requests in

    <template>
      <div>
        <h1> Personal information </h1>
        {{ id }}
      </div>
    
    </template>
    
    <script>
    export default {
      name: "UserProFile",
      props: ['id'],
      beforeRouteEnter: (to, from, next) => {
        console.log(' Before entering the route ');// Load data 
        next(vm => {
          vm.getData();// Before entering the route getData()
        })
      },
      beforeRouteLeave: (to, from, next) => {
        console.log(' After leaving the route ');
        next()
      },
      methods: {
        getData:function () {
          this.axios({
            method: 'get',
            url: 'http://localhost:8080/static/mock/data.json'
          }).then(function (response){
            console.log(response)
          })
        }
      }
    }
    </script>
    
    <style scoped>
    
    </style>