preface

Routing is to display different pages or content through different URLS. Vue routing is the unified management of all content URL address intermediate station, and then according to different modules to jump

1.router-link

  • Similar to the A tag, you can change the URL without reloading the page
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script><div id="app"> <h1>Hello world! </h1> <p> <! -- Use the router-link component for navigation --> <! -- Specify links by passing 'to' --> <! -- '<router-link>' will render a '<a>' tag with the correct 'href' attribute --> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <! -- Routing exit --> <! <router-view></router-view> </div>Copy the code

2.router-view

  • Router-view displays the component corresponding to the URL

// 1. Define the routing component
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }


// 2. Define multiple routes
const routes = [
  { path: '/'.component: Home },
  { path: '/about'.component: About },
]

// 3. Create a routing instance and routes configuration
const router = VueRouter.createRouter({
  // 4. The implementation of the history mode is provided internally. Using hash Mode
  history: VueRouter.createWebHashHistory(),
  routes, // 'routes: short for routes'
})

// 5. Create a mount instance
const app = Vue.createApp({})
app.use(router); // It can be accessed from any component as this.$router and the current route as this.$route
app.mount('#app')
Copy the code
// Home.vue
export default {
  computed: {
    username() {
      // Get the params value
      return this.$route.params.username
    },
  },
  methods: {
    goTest() {
      if (isAuthenticated) {
        this.$router.push('/dashboard')}else {
        this.$router.push('/login')}},},}Copy the code

3. Set routine by

  • Nested paths starting with/are treated as root paths. Allows component nesting without having to use nested urls
const router = new VueRouter({
  routes: [{path: '/user/:id'.component: User,
      children: [
        // If /user/:id matches successfully,
        // The UserHome will be rendered in User's 
      
        { path: ' '.component: UserHome },

        / /... Other child routes]]}})Copy the code

4. Dynamic routes

  • Dynamic routing is an application scenario that encapsulates a component and reuses it to match multiple paths
  • Dynamic route matching with parameters
const User = {
  template: '<div>User</div>',}// These will be passed to 'createRouter'
const routes = [
  // The dynamic segment starts with a colon
  { path: '/users/:id'.component: User },
]

// Read route :id
const User = {
  template: '<div>User {{ $route.params.id }}</div>',}// Matching mode = > Matching path = > $route.params: / users/username = > / users /eduardo= > { username: 'eduardo'} / users/username/posts / : postId = > / users/eduardo/posts /123= > {username: 'eduardo'.postId: '123' }

Copy the code
  • Responds to changes in routing parameters
const User = {
  template: '... '.created() {
    this.$watch(
      () = > this.$route.params,
      (toParams, previousParams) = > {
        // Respond to routing changes...}})},// Or use the beforeRouteUpdate navigation guard, which can also unnavigate:
const User = {
  template: '... '.async beforeRouteUpdate(to, from) {
    // Respond to routing changes...
    this.userData = await fetchUser(to.params.id)
  },
}
Copy the code

5. Programmed navigation

  • Routing instances can be accessed through the Router. So you can call this.router to access the routing instance. So you can call this.router to access the routing instance. So you can call this.router.push.
/ / the declarative
<router-link :to="...">
/ / programmatic
router.push(...)


// String path
router.push('/users/eduardo')

// Object with path
router.push({ path: '/users/eduardo' })

// A named route with an argument to make way for the url to be created
router.push({ name: 'user'.params: { username: 'eduardo'}})// register? plan=private
router.push({ path: '/register'.query: { plan: 'private'}})// Hash, the result is /about#team
router.push({ path: '/about'.hash: '#team' })
Copy the code
  • If the route provides a path, the params will be ignored
const username = 'eduardo'
// We can set up the URL manually, but we have to handle the encoding ourselves
router.push(`/user/${username}`) // -> /user/eduardo
/ / the same
router.push({ path: `/user/${username}` }) // -> /user/eduardo
// If possible, use 'name' and 'params' to benefit from automatic URL encoding
router.push({ name: 'user'.params: { username } }) // -> /user/eduardo
// 'params' cannot be used with' path '
router.push({ path: '/user'.params: { username } }) // -> /user
Copy the code

Because the attribute to accepts the same kind of object as router.push, the rules for both are exactly the same.

Replace the current position

  • It acts like router.push, except that it doesn’t add a new record to history as it navigates, as its name suggests — it replaces the current entry.
/ / the declarative
<router-link :to="..." replace>
/ / programmatic
router.replace(...)
// You can also add a routeLocation attribute directly to the routeLocation passed to router.push. Replace: true:


router.push({ path: '/home'.replace: true })
/ / equivalent to
router.replace({ path: '/home' })
Copy the code

Route History mode window.history.go(n).

// Move a record forward, the same as router.forward()
router.go(1)

// Return a record, the same as router.back()
router.go(-1)

// Forward 3 records
router.go(3)

// Silence fails if there are not so many records
router.go(-100)
router.go(100)
Copy the code

6. Name a route

  • Advantages of named routes:

1. No hard-coded URL 2. Automatic encoding/decoding of Params. 3. Prevent typing errors in urls. 4. Bypass path sort (e.g., display one)

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Home = { template: '<div>This is Home</div>' }
const Foo = { template: '<div>This is Foo</div>' }
const Bar = { template: '<div>This is Bar {{ $route.params.id }}</div>' }

const router = new VueRouter({
  mode: 'history'.base: __dirname,
  routes: [{path: '/'.name: 'home'.component: Home },
    { path: '/foo'.name: 'foo'.component: Foo },
    { path: '/bar/:id'.name: 'bar'.component: Bar }
  ]
})

new Vue({
  router,
  template: ` 
      

Named Routes

Current route name: {{ $route.name }}

  • home
  • foo
  • bar
`
}).$mount('#app') Copy the code

1. Name the view

  • A view renders with one component, so multiple views require multiple components for the same route. Make sure to use the Components configuration correctly (with s) :
<router-view class="view left-sidebar" name="LeftSidebar"></router-view>
<router-view class="view main-content"></router-view>
<router-view class="view right-sidebar" name="RightSidebar"></router-view>


const router = createRouter({
  history: createWebHashHistory(),
  routes: [{path: '/'.components: {
        default: Home,
        // LeftSidebar: short for LeftSidebar
        LeftSidebar,
        // They match the 'name' attribute on '
      
       '
      
        RightSidebar,
      },
    },
  ],
})
Copy the code
Copy the code

2. Nested named views

<! -- UserSettings.vue --><div>
  <h1>User Settings</h1>
  <NavBar />
  <router-view />
  <router-view name="helper" />
</div>

/ / routing
{
  path: '/settings'.// You can also configure named views on top-level routes
  component: UserSettings,
  children: [{
    path: 'emails'.component: UserEmailsSubscriptions
  }, {
    path: 'profile'.components: {
      default: UserProfile,
      helper: UserProfilePreview
    }
  }]
}
Copy the code

7. Route components send parameters

  • The Boolean model

When the props is set to true, route.params is set to the props of the component.

  • Named view
// For routes with named views, you must define the props configuration for each named view:
const routes = [
  {
    path: '/user/:id'.components: { default: User, sidebar: Sidebar },
    props: { default: true.sidebar: false}}]Copy the code
  • Object pattern

When props is an object, it sets as-is to component props. This is useful when props are static.

const routes = [
  {
    path: '/promotion/from-newsletter'.component: Promotion,
    props: { newsletterPopup: false}}]Copy the code
  • The function mode

You can create a function that returns props. This allows you to convert parameters to other types, combine static values with route-based values, and so on.

const routes = [
  {
    path: '/search'.component: SearchUser,
    props: route= > ({ query: route.query.q })
  }
]
// URL /search? Q =vue passes {query: 'vue'} as props to the SearchUser component.
Copy the code

References:

Vue routing basics