current position:Home>Vue - 12 - Vue route

Vue - 12 - Vue route

2022-01-27 01:26:40 Nanchen_ forty-two

Catalog

vue-router Dynamic routing for

solve ElementUI In the navigation bar vue-router stay 3.0 There is an error in the repeated click menu above the version  

vue-router Parameter transfer of  

There are two main types of passing parameters :params and query


vue-router What is it?

The routing here does not refer to the hardware router as we usually call it , The route here is SPA( A single page application ) Path manager for . Let's talk about it more generally ,vue-router Namely WebApp Link path management system of .
vue-router yes Vue.js The official routing plug-in , It and vue.js It's deeply integrated , Suitable for building single page applications .vue Our single page application is based on Routing and components , Routing is used to set the access path , And map the path to the component . Traditional page applications , Is to use some hyperlinks to achieve page switching and jump . stay vue-router Single page application , It's the switch between paths , That is, the switching of components . The essence of routing module Is to build url Mapping between and pages .

As for why we can't use it a label , This is because of the use of Vue It's all single page applications ( When your project is ready to be packaged , function npm run build when , Will generate dist Folder , There are only static resources and one index.html page ), So you wrote <a></a> Labels don't work , You have to use vue-router To manage .

install Vue-Router It needs to be installed before The scaffold

cnpm install vue-router

perhaps

vue add router 

  stay src The new one in is called router Create a new folder index.js file

stay src The new one in is called views Create a new folder About.vue and Home.vue file

index.js part

Bear in mind !!!routes No wrong number  

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [{
  //  When I input / Will redirect to home in 
    path: '/',
    redirect: '/about'
  },
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import( /* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})

export default router

About.vue Code :

<template>
    <div> I'm about the page </div>
</template>

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

<style>
</style>

Home.vue The code is as follows :

<template>
  <div> I'm home page </div>
</template>

<script>
export default {
  name: "Home",
};
</script>

<style>
</style>

App.vue The code in is as follows :

<template>
  <div id="app">
    <div id="nav">
      <!-- <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> -->
      <button @click="home">Home</button>
      <button @click="about">About</button>
    </div>
    <router-view />
  </div>
</template>
<script>
export default {
  data(){
    return {}
  },
  methods:{
    home(){
    // this.$router.push('/')
    // this.$router.push({ path: '/' })
    // this.$router.push('Home')
    this.$router.push({name:'Home'})
  },
  about(){
    this.$router.push('/about')
  }
  }
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

main.js The documents are as follows :

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

Vue.config.productionTip = false

new Vue({
  router,
  open:true,
  hot:true,
  render: h => h(App)
}).$mount('#app')

Using routing : adopt <router-link> and <router-view>

<router-link> It's a global component , It's finally rendered as a label , however <router-link> Just mark the route to something like a Like a label or a button , But we click a Tag to jump to page or to display page , So we need to use <router-view>.

<router-view>  It's for space , This is where the components corresponding to the route are displayed , The tag will be based on the current path , Dynamic rendering of different components .

When the route is switched, the switch is <router-view> Mounted components , Nothing else will change .

<router-view> By default hash Pattern , Can be in index.js The configuration in is modified to history Pattern .

app.vue modify template

<router-link> Other properties of

  • to attribute : Used to jump to the specified path .
  • tag attribute : You can specify <router-link> What components are rendered to use <router-link to='/home' tag='button'> Will be rendered as a button , instead of a label .
  • relapce attribute : stay history Specify... In mode <router-link to='/home' tag='button' replace> Use replaceState instead of pushState, At this time, the browser's return button cannot be used .
  • active-class attribute : When <router-link> When the corresponding route matches successfully , Will automatically set a router-link-active Of class, Set up active-class You can change the default name .
  • In the highlighted navigation menu or at the bottom tabbar when , This attribute will be used
  • But you don't usually change the properties of a class , Will use the default router-link-active
  • <router-link to='/home' tag='button' active-class='active'> The one chosen at this time <router-link> There will be active Of class.
  • If each <router-link> All have to be added. active-class='active', Then make unified changes in the route . 
    <!--  Route exit  -->
    <!--  The component to which the route matches is rendered here  -->
    <router-link to="/">home</router-link>  |
    <router-link to="/about">about</router-link>
    <router-view></router-view>        <!--  Show page elements  -->

Of course ,router-view The tag can be abbreviated as the following code , Be careful :/ rearwards

<router-view/>

Launch the browser

npm run  serve

The effect is as follows : 

 

modify hash The model is history Pattern , modify index.js Of router object  

const router = new VueRouter({
  // Configure the application relationship between routing and components 
  routes,
  mode: 'history'// The modification mode is history
})

At this point, you will find the address bar of the browser URL It's not # Of .

Switch tab functions : 

  linkExactActiveClass:'active' 

  to active Of class Plus the font turns red css.

 

  There's no need to router-link Tags can also realize page Jump

stay Vue Router The website says , When you click <router-link> when , This method will call... Internally , So , Click on <router-link :to="..."> Equivalent to calling router.push(...).

You can also use vue ui To install directly

If you use vue ui There is no need to create a new installation router Folders and views Folder and other contents

Configure the code format after installation

  After the configuration is completed, a js file

  Modify... In the file

module.exports = {
  lintOnSave: false,
  devServer: {
    //  Path after project construction 
    // contentBase: resolve(__dirname, 'build'),
    //  start-up gzip Compress 
    compress: true,        // Whether to turn on compression 
    //  Port number 
    port: 3000,
    //  Open browser automatically 
    open: true,
    hot:true
  },
  
}

You can automatically open the browser and render it in real time

vue-router Dynamic routing for

One page path The path may be uncertain , For example, there may be /user/aaaa perhaps /user/bbbb, except /user outside , Followed by users ID/user/123 etc. . such path and component The match of , It's called dynamic routing .

Create a new component User

<template>
  <div>
    <h1>User:{
   {UserId}}</h1>
  </div>
</template>

<script>
export default {
  name: 'User',
  computed:{
      UserId(){
          return this.$route.params.UserId
      }
  }
}
</script>

stay App.vue Medium template Add the following code to the tag

      <router-link :to="/User/ + UserId">User</router-link> 

script part : 

export default {
  data() {
    return {
      UserId: '1024',
    };
  },
}

  Nested Route :

 

Nested routing is to switch two small pages in one page  

You can write these two components to components In the folder

  Create two new files, namely HomeMessage as well as HomeNew.vue

HomeMessage.vue The contents are as follows :

<template>
    <div>
        <ul>
            <li v-for="(item,index) in arr" :key="index">{
   {item}}</li>
        </ul>
    </div>
</template>
<script>
export default {
    name:'HomeMessage',
    data() {
        return {
            arr: ['a,b,c,d,e,f,g,h,i,j'],
        };
    },
}
</script>

HomeNews.vue The code is as follows :

<template>
    <div>
        <ul>
            <li v-for="(item,index) in arr" :key="index">{
   {item}}</li>
        </ul>
    </div>
</template>
<script>
export default {
    name:'HomeNews',
    data() {
        return {
            arr: ['1,2,3,4,5,6,7,8,9,10'],
        };
    },
}
</script>

stay router Medium index.js Of home Add the following code in

children: [{
        path: '/',
        redirect: '/home/homenews'
      },
      {
        path: '/home/homenews',
        name: 'HomeNews',
        component: () => import('@/components/HomeNews')
      },
      {
        path: '/home/homemessage',
        name: 'HomeMessage',
        component: () => import('@/components/HomeMessage')
      },
    ]

  Last in home.vue Introduce these two components into

<template>
  <div class="home">
    <h1>Home</h1>
    <router-link to="/home/homenews">HomeNews</router-link>|
      <router-link to="/home/homemessage">HomeMessage</router-link>
      <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'Home',
}
</script>

solve ElementUI In the navigation bar vue-router stay 3.0 There is an error in the repeated click menu above the version  

//  solve ElementUI In the navigation bar vue-router stay 3.0 There is an error in the repeated click menu above the version 
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

vue-router Parameter transfer of  

  newly build Profile.vue page

<template>
    <div>
        <h2> File page </h2>
        <p> The name is :{
   {profileInfo.name}}</p>
        <p> The gender is :{
   {profileInfo.sex}}</p>
        <p> Height is :{
   {profileInfo.height}}</p>
    </div>
</template>
<script>
export default {
    name:"Profile",
    computed:{
        profileInfo(){
        return this.$route.query.profileInfo
    }
    }
}
</script>

index.js part

  {
    path: '/profile',
    name: 'Profile',
    meta:{title:' archives '},
    component: () => import('@/views/Profile')
  }

 App.vue part

Component part : 

<router-link :to="{ path: '/profile', query: { profileInfo } }"> archives </router-link>

script part : 

export default {
  data() {
    return {
      UserId: "1024",
      profileInfo: {
        name: "NC",
        age: 24,
        height: 188,
      },
    };
  },
};

There are two main types of passing parameters :params and query

params The type of is dynamic routing

  • Configure the format of the route :/user/:userId
  • The way of transmission : stay path Follow the corresponding userId
  • The path formed by transmission :/user/123,/user/xxx
  • adopt $route.params.userId Get specified userId

query The type of

  • Configure the format of the route :/profile, That is, the normal configuration
  • The way of transmission : Use in object query Of key As a means of transmission
  • The path formed by transmission :/profile?name=NC&age=24&height=188( This passes three key value pairs ),/profile?profileInfo=%5Bobject%20Object%5D This query What is passed is the key value pair of an object ,key by profileInfo,value It's an object )

name With params

path With query 

  Full effect :

 About.vue Code :

<template>
  <div class="about">
    <h1>This is an about page</h1>
  </div>
</template>
<script>
export default {
  name:'About'
}
</script>

Home.vue Code :

<template>
  <div class="home">
    <h1>Home</h1>
    <router-link to="/home/homenews" tag="button">HomeNews</router-link> |
      <router-link to="/home/homemessage" tag="button">HomeMessage</router-link>
      <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'Home',
}
</script>
<style scoped>
.active{
  background-color: rgb(226, 99, 99);
  color: white;
}
</style>

Profile.vue Code :

<template>
  <div>
    <h1> File page </h1>
    <p> The name is :{
   { profileInfo.name }}</p>
    <p> The gender is :{
   { profileInfo.sex }}</p>
    <p> Height is :{
   { profileInfo.height }}</p>
  </div>
</template>
<script>
export default {
  name: "Profile",
  mounted() {
    console.log(this.$route);
  },
  computed: {
    profileInfo() {
      return this.$route.query.profileInfo;
    },
  },
};
</script>
<style  scoped>
p {
  margin: 10px;
}
</style>

User.vue Code :

<template>
  <div>
    <h1>User:{
   { UserId }}</h1>
  </div>
</template>

<script>
export default {
  name: "User",
  computed: {
    UserId() {
      return this.$route.params.UserId;
    },
  },
};
</script>

App.vue Code :

<template>
  <div id="app">
    <div id="nav">
      <!-- <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link :to="/User/ + UserId">User</router-link> |
      <router-link :to="{ path: '/profile', query: { profileInfo } }"> archives </router-link> -->
      <button @click="goHome">Home</button> |
      <button @click="goAbout">About</button> |
      <button @click="goUser">User</button> |
      <button @click="profileClick"> archives </button>
    </div>
    <router-view />
  </div>
</template>
<script>
export default {
  data() {
    return {
      UserId: "1024",
      profileInfo: {
        name: "NC",
        sex: " male ",
        height: 188,
      },
    };
  },
  methods: {
    goHome() {
      this.$router.push("/");
    },
    goAbout() {
      this.$router.push("/about");
    },
    goUser() {
      this.$router.push({
        name: "User",
        params: {
          UserId: this.UserId,
        },
      });
    },
    profileClick() {
      this.$router.push({
        path: "/profile",
        query: {
          profileInfo: this.profileInfo,
        },
      });
    },
  },
};
</script>
<style>
* {
  margin: 0;
  padding: 0;
}
ul {
  list-style-type: none;
}
a {
  text-decoration: none;
  color: #2c3e50;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
#nav {
  padding: 30px;
}
#nav a {
  font-weight: bold;
  color: #2c3e50;
}
#nav a.router-link-exact-active {
  color: #42b983;
}
button {
  width: 120px;
}
.active {
  background-color: rgb(226, 99, 99) !important;
  color: white !important;
}
</style>

components Under folder HomeNews.vue Code :

<template>
  <div>
    <br />
    <ul>
      <li v-for="(item, index) in arr" :key="index">{
   { item }}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "HomeNews",
  data() {
    return {
      arr: ["1,2,3,4,5,6,7,8,9,10"],
    };
  },
};
</script>

HomeMessage.vue Code :

<template>
  <div>
    <br />
    <ul>
      <li v-for="(item, index) in arr" :key="index">{
   { item }}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "HomeMessage",
  data() {
    return {
      arr: ["a,b,c,d,e,f,g,h,i,j"],
    };
  },
};
</script>

index.js Code :

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [{
    path: '/',
    name: 'Home',
    component: Home,
    children: [{
        path: '/',
        redirect: '/home/homenews'
      },
      {
        path: '/home/homenews',
        name: 'HomeNews',
        component: () => import('@/components/HomeNews')
      },
      {
        path: '/home/homemessage',
        name: 'HomeMessage',
        component: () => import('@/components/HomeMessage')
      },
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import( /* webpackChunkName: "about" */ '@/views/About.vue')
  },
  {
    path: '/user/:UserId',
    name: 'User',
    component: () => import('@/views/User')
  },
  {
    path: '/profile',
    name: 'Profile',
    meta: {
      title: ' archives '
    },
    component: () => import('@/views/Profile')
  }
]
// src/router/index.js
const router = new VueRouter({
  routes,
  mode: 'history',
  linkExactActiveClass: 'active'
})
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

export default router

The structure is as follows :

copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270126372066.html

Random recommended