Route at the front end




Content summary

  • Know routing
  • Basic use of vue-router
  • vue-router nested routing
  • Vue-router parameter passing
  • vue-router navigation guard
  • keep-alive


1. Routing

Insert picture description here


  • The routing mapping table maps the IP address of the intranet to the unique computer mac address.
  • The essence of the routing table is a mapping table, which determines the direction of the data packet

1. The difference between front-end rendering and back-end rendering

The current development is to use js+html+css, but in the early days, there was no such code as js. It passes the code on the back end directly after rendering, and then passes it to the front end. In other words, what he passes to the front end is already html+css.

Insert picture description here




1. Back-end rendering and back-end routing:

The one-to-one correspondence between the routing address and the table is completed by the backend, and this routing method is called backend routing.
Back-end routing uses the back-end programmer's own logic java or php to nest data in html web pages.

Insert picture description here



Front-end rendering (after using ajax, you can access the database through js.)

Insert picture description here



SPA page:

spa single page rich application

In fact, when you make a request to the static resource server for the first time, you have already brought all the html + css web pages, so every time you click on the route, you don’t send any request to the backend. Just change your interface, this kind of routing is called front-end routing.

Insert picture description here



2. How to change the url, the page does not refresh

One of the techniques is to change the url by changing the hash. At this time, the page does not refresh

location.hash='aaa'

3. Configure front-end routing


Insert picture description here

import Vue from 'vue'

//导入路由
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

// 任何插件,都要使用 vue.use(Router)的方法使用。
Vue.use(Router)


// 把 Router 实例导出。
export default new Router({
    
    
  routes: [
    {
    
    
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})




Four. Configure front-end routing

import Vue from 'vue'
import Home from '../components/Home.vue'
import About from '../components/About.vue'

//导入路由
import Router from 'vue-router'


// 任何插件,都要使用 vue.use(Router)的方法使用。
Vue.use(Router)


// 把 Router 实例导出。
export default new Router({
    
    
  routes: [
    // {
    
    
    //   // path: '/',
    //   // name: 'HelloWorld',
    //   // component: HelloWorld
    // },
    {
    
    
      path: "/home",
      component: Home
    },
    {
    
    
      path: "/about",
      component: About
    }
  ]
})

Recognize two tags:

<router-link to >It is named for routing address, and router-viewrouting exports that used to represent this route should be displayed in any place.

<template>
  <div id="app">
    <!-- 相当于是一个 a 标签 -->
    <router-link to="/home">首页</router-link>
    <router-link to="/about">关于</router-link>
    
     <!-- 相当于在显示的地方占个位置 -->
    <router-view></router-view>
  </div>
</template>

Five. Configure the default route

If you enter a web page every time, every click Home to jump to the home, very convenient, therefore, should be configured route and let him jump to the default home page

Add this to the route

{
    
    
      //打开的时候,默认重定向
      path: '',
      redirect: '/home' //重定向
    },

The routing address will have a # key when it is used. This is because the hash method is used by default, and we can change it to the history method. code show as below:

When configuring the routing instance, pass in one more parameter:

Insert picture description here




6. Change the relevant attributes of router-link

By default, router-link is in the style of a tag, but it can also be replaced with tags such as button. At the same time, you can change the color effect when clicked, the specific code is as follows,

<template>
  <div id="app">
    <!-- 相当于是一个 a 标签 -->
    <router-link to="/home" tag="button">首页</router-link>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
     
     
  name: 'App'
}
</script>

<style>
/* 点击的时候变颜色 */
.router-link-active{
     
     
  color: brown;
}
</style>



7. Dynamic path parameters (dynamic routing)

First of all, it is clear what is dynamic routing, dynamic routing is to dynamically display the routing address according to the difference of each person who clicks


Insert picture description here

For specific implementation, look at the code:

1. First build a component: User, register him in the route, pay attention to the structure (use: to indicate)

{
    
    
      path: "/user/:userId",
      component: User
    },

2. Then in the APP display interface, use the splicing method to make it dynamically displayed

<template>
  <div id="app">
    <!-- 相当于是一个 a 标签 -->
    <router-link to="/home" tag="button">首页</router-link>
    <router-link to="/about">关于</router-link>

    //动态路由的拼接,是从 data 里面获取数据的
    <router-link :to="'/user/'+userId">用户</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
     
     
  name: 'App',
  data(){
     
     
    return{
     
     
      userId:'zhangshan'
    }
  }
}
</script>

<style>
/* 点击的时候变颜色 */
.router-link-active{
     
     
  color: brown;
}
</style>

3. In the view layer, let the displayed route be displayed.

By injecting a router, we can in any component this.$routerto access the router, you can also this.$routeaccess the current route:

<template>
  <div>
    <h1>我是用户界面</h1>
    <p>我是用户界面的内容,哈哈</p>

    <!-- 通过下边的 computed 的userId 方法,把路由里面的参数取出来 -->
    <h2>{
   
   {userId}}</h2>

    <!-- 也可以直接拿出来 -->
    <h3>{
   
   {$route.params.userId}}</h3>
  </div>
</template>

<script>
export default {
     
     
  name: "User",
  computed: {
     
     
    userId() {
     
     
      //  $route 就是拿到当前的处于活跃状态的路由
      return this.$route.params.userId;
    },
  },
};
</script>

<style  scoped>
</style>

4. Note: After testing by myself, Chinese names can always appear in the router

5. Capture all routes and 404 error pages

Regular parameters will only match characters in URL fragments separated by /. If you want to match any path, we can use wildcards (*):
When using wildcard routing, please make sure that the order of the routing is correct, that is to say, the routing with wildcards should be placed last. Routing { path: '*' }is usually used for client 404. If you use History mode, make sure to configure your server correctly.



8. Lazy loading of routing

When building an application by packaging, the Javascript package will become very large, which will affect the loading. If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed, it will be even more It's efficient.

Code: (very simple)

You only need to change the above wording to the following wording when importing the module in the routing example:

import About from '../components/About.vue'

const About=()=>import('../components/About.vue')



Nine. Nested routing

The nesting of routing is used to indicate the relationship between nested sub-components in the component

note. There are certain requirements on whether to add / in the routing, it is not added randomly.

step:

  • Create the corresponding sub-components and configure the corresponding sub-routes in the route map.
  • Use <router-view> in the routing component, label


Create subcomponent

Note that the naming of sub-components should show the parent-child relationship.

Refer to the component in the route, the code is as follows:


const HomeMessage =()=>import("../components/HomeMessage.vue")
const HomeNews =()=>import("../components/HomeNews.vue")

// 任何插件,都要使用 vue.use(Router)的方法使用。
Vue.use(Router)

// 把 Router 实例导出。
export default new Router({
    
    
//把更改hash 值得写法,更改为 history 的写法, 就没有了 #
  mode: 'history',
  routes: [
    {
    
    
      //打开的时候,默认重定向
      path: '',
      redirect: '/home' //重定向
    },
    {
    
    
      path: "/user/:userId",
      component: User
    },
    {
    
    
      path: "/home",
      component: Home,
      children:[
        {
    
    
          path:'',
          redirect:'news'
        },
        {
    
    
          path:'news',
          component:HomeNews
        },
        {
    
    
          path:'message',
          component:HomeMessage
        }
      ]
    },
    {
    
    
      path: "/about",
      component: About
    },]})


Add the <router-view> tag

Note that the routing here must write the complete routing address:

<template>
  <div>
      <h2>我是Home,哈哈</h2>
      <p>我是内容,哈哈</p>

      <br>
      <router-link to="/home/news">新闻</router-link>
      <router-link to="/home/message">消息</router-link>
      <router-view></router-view>
  </div>
</template>


X. Global navigation guard

The specific function of this function is to use the global navigation guard, when switching between different components, the name of the component can be dynamically displayed on the route.


11. vue-router-keep-alive

To understand the life cycle, the code is as follows:

<script>
export default {
    
    
  name: "Home",
  data() {
    
    
    return {
    
    };
  },

  // 创建的时候调用
  created() {
    
    
    console.log("created");
  },

  // 销毁的时候,调用
  destroyed() {
    
    
    console.log("destroyed");
  },
};
</script>

The effect is that when the interface jumps, different life cycle functions will be displayed and the corresponding function will be called.

Specific functions to be realized: After clicking on the corresponding webpage, when you come back, the page is still saved in the original state just now.

Insert picture description here


Directly on the label to show the route, plus <keep-alive>you can

  <keep-alive>
      <router-view />
  </keep-alive> 





12. Routing and parameter transfer

<router-link :to="{name:'/test',params: {id: id}}">跳转</router-link>

Get in subcomponent

this.$route.params.id



13. Programmatic navigation

Want to navigate to a different URL, use the router.pushmethod. This method will add a new record to the history stack, so when the user clicks the browser back button, it will return to the previous URL.

When you click <router-link>, this method will be called internally, so clicking is <router-link :to="...">equivalent to calling router.push(...).

Create a route first

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})

Pass parameters through named components

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

The above code and the following have the same meaning.

router.push({
    
     name: 'user', params: {
    
     userId: 123 }})

Usage of router.go(n)

// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)

Guess you like

Origin blog.csdn.net/zhaozhao236/article/details/109356758