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 and @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. 将路由注入到Vue对象中
  5. 在根组件中使用<router-link>定义跳转路径
  6. 在根组件中使用<router-view>来渲染组件
  7. 创建子组件

三、路由的跳转

router-link

router-link标签用于页面的跳转,简单用法如上demo

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

点击这个router-link标签router-view就会渲染路径为/page01的页面。
注意:router-link默认是一个a标签的形式,如果需要显示不同的样子,可以在router-link标签中写入不同标签元素,如下显示为button按钮。

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

router.push

下面我们通过JS代码控制路由的界面渲染,官方是写法如下:

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

那么问题来了,如果是全局注册的路由Vue.use(VueRouter),应该怎么写呢?

// 字符串
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' }})

push方法其实和<router-link :to="...">是等同的。
注意:push方法的跳转会向 history 栈添加一个新的记录,当我们点击浏览器的返回按钮时可以看到之前的页面。

router.replace

push方法会向 history 栈添加一个新的记录,而replace方法是替换当前的页面,不会向 history 栈添加一个新的记录。用法如下
template

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

script

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

router.go

go方法用于控制history记录的前进和后退

// 在浏览器记录中前进一步,等同于 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)

其实很好理解:go方法就是浏览器上的前进后退按钮,后面的参数就是前进和后退的次数

四、路由的传参方式

在路由跳转的过程中会传递一个object,我们可以通过watch方法查看路由信息对象。

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

console中看到的路由信息对象

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

这两个参数会在页面跳转后写在路径中,路径相当于/page/123?name=jack

1. params

其实这个params我还是有一些疑惑的,就比如下面的写法:

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

传递过去的数据却没有包含params的数据。

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

下面是我暂时调试成功的一些结论。

传递数据

在路由配置文件中定义参数

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

路径后面的/:sex就是我们要传递的参数。

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

此时路由跳转的路径

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

此时我们看到查看路由信息对象:

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

获取数据

template

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

script

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

注:暂时我只发现在动态路由匹配中传入数据可以获取到params。而使用{ path: '/', params: { sex: '123' }, query: { ...}}传递的数据使用没有传递给下一个页面组件。如果有使用成功的同学欢迎在留言,我会及时更正的。

2. query

query传递数据的方式就是URL常见的查询参数,如/foo?user=1&name=2&age=3。很好理解,下面就简单写一下用法以及结果

传递数据

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' }})

路径结果

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

路由信息对象

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

获取数据

获取数据和params是一样的。
template

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

script

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

Vue.js学习系列项目地址

https://github.com/violetjack/VueStudyDemos

Vue.js学习系列

Guess you like

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