Vue.js2 routing learning 2

If you want to learn Vue's SPA application, routing is essential. I believe that many friends who are new to the front end like me are very confused about routing. So after I learned and successfully used vue-router, I will share my personal experience, hoping to help students who are also overwhelmed by routing.

Notice:

1. Routing installation:

npm install

Plugins can be installed directly using npm

npm install vue-router --save

Execute the command to complete the installation of vue-router, and add the vue-router dependency in package.json. When we install the project on other computers, we only need to execute npm installto complete the installation. (Thanks to @waynezheng, @hao brother for pointing out the issue about dependency, which has been corrected ^-^.)

package.json

  "dependencies": {
    ...
    "vue-router": "^2.1.1"
    ...
  },

If you are installing in a development environment, use the following command line:

npm install vue-router --save-dev

package.json

  "devDependencies": {
    ...
    "vue-router": "^2.1.1",
    ...
  },

2. Simple implementation of routing in SPA (with demo)

Let's configure routing and implement our first page jump.
The demo provided by the official is very simple, and it can indeed run when copied into HTML, but the problem is that I don't know how to use it in SPA applications, which took me a lot of time. After reading a lot of other people's projects, I completed a simple demo of SPA routing (webpack template based on vue-cli).
main.js

import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import Page01 from './components/page01'
import Page02 from './components/page02'

Vue.use(VueRouter)//全局安装路由功能
//定义路径
const routes = [
  { path: '/', component: Page01 },
  { path: '/02', component: Page02 },
]
//创建路由对象
const router = new VueRouter({
  routes
})

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  router
})

App.view

<template>
  <div id="app">
    <router-link to="/">01</router-link>
    <router-link to="/02">02</router-link>
    <br/>
    <router-view></router-view>
  </div>
</template>

page01.view

<template>
  <div>
    <h1>page02</h1>
  </div>
</template>

page02.view

<template>
  <div>
    <h1>page02</h1>
  </div>
</template>

The code is very simple, you can see the DEMO
implementation steps for details:

  1. npmInstallvue-router
  2. Vue.use(VueRouter)Install Routing Feature Globally
  3. Define an array of paths routesand create a route objectrouter
  4. Inject routes into Vue objects
  5. In the root component use <router-link>define jump paths
  6. Used in the root component <router-view>to render the component
  7. Create child components

3. Routing jump

router-link

router-linkLabels are used for page jumps, the simple usage is as above demo

<router-link to="/page01">page01</router-link>

Clicking on this router-linktag router-viewrenders the page with path /page01.
Note:router-link The default is in the form of an a tag. If you need to display a different look, you can router-linkwrite different tag elements in the tag, as shown below as a buttonbutton.

<router-link to="/04">
    <button>to04</button>
</router-link>

router.push

Next, we control the interface rendering of routing through JS code. The official way is as follows:

// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

So the question is, if it is a globally registered route Vue.use(VueRouter), how should it be written?

// 字符串
this.$router.push('home')
// 对象
this.$router.push({ path: 'home' })
// 命名的路由
this.$router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
this.$router.push({ path: 'register', query: { plan: 'private' }})

The push method is actually <router-link :to="...">equivalent to .
Note: The jump of the push method will add a new record to the history stack. When we click the back button of the browser, we can see the previous page.

router.replace

The push method adds a new record to the history stack, and the replace method replaces the current page without adding a new record to the history stack. The usage is as follows
template

<router-link to="/05" replace>05</router-link>

script

this.$router.replace({ path: '/05' })

router.go

The go method is used to control the forward and backward of the history record

// 在浏览器记录中前进一步,等同于 history.forward()
this.$router.go(1)
// 后退一步记录,等同于 history.back()
this.$router.go(-1)
// 前进 3 步记录router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
this.$router.go(-100)
this.$router.go(100)

In fact, it is easy to understand: the go method is the forward and backward buttons on the browser, and the following parameters are the number of forward and backward

4. The way of routing parameters

In the process of routing jump, an object will be passed, and we can watchview the routing information object through the method.

watch: {
  '$route' (to, from) {
      console.log(to);
      console.log(from);
  },
},

The routing information object seen in the console

{
    ...
    params: { id: '123' },
    query: { name: 'jack' },
    ...
}

These two parameters will be written in the path after the page jumps, and the path is equivalent to/page/123?name=jack

1. params

In fact, I still have some doubts about this params, such as the following way of writing:

 <router-link :to="{ path: '/05', params: { sex: 'hello param', sex2: 'hello param2' }, query: { name: 'hello query', name2: 'hello query2' }}">05</router-link>

Passed past data but no data containing params.

{
    ...
    params: {},
    query: {
        name: 'hello query',
        name2: 'hello query2'
    }
    ...
}

The following are some conclusions I have temporarily debugged successfully.

pass data

Define parameters in routing configuration file

  //命名路由&路由传参
  { name: 'com03', path: '/03/:sex', component: Page03 },

After the path /:sexis the parameter we want to pass.

this.$router.push({ path: '/03/441'})

The path that the route jumps to at this time

http://localhost:8080/#/03/441

At this point we see the view routing information object:

{
    ...
    params: {
        sex: '441'
    }
    ...
}

retrieve data

template

<h2> {{ $route.params.sex }} </h2>

script

console.log(this.$route.params.sex)

Note: For the time being, I only found that params can be obtained by passing data in dynamic route matching . While using { path: '/', params: { sex: '123' }, query: { ...}}the passed data use is not passed to the next page component. If there are students who have successfully used it, please leave a message and I will correct it in time.

2. query

The way query passes data is the common query parameters of URLs, such as /foo?user=1&name=2&age=3. It's easy to understand, let's briefly write the usage and results below

pass data

template

<router-link :to="{ path: '/05', query: { name: 'query', type: 'object' }}" replace>05</router-link>

script

this.$router.replace({ path: '/05', query: { name: 'query', type: 'object' }})

path result

http://localhost:8080/#/05?name=query&type=object

routing information object

{
    ...
    query: {
        name: "query",
        type: "object"
    }
    ...
}

retrieve data

Getting data is the same as params.
template

<h2> {{ $route.query.name }} </h2>

script

console.log(this.$route.query.type)

Vue.js learning series project address

https://github.com/violetjack/VueStudyDemos

Vue.js learning series

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326270613&siteId=291194637