![](https://img.haomeiwen.com/i11445944/68d53cb302c997b0.png)
使用vue-router实现前端路由
安装vue-router:
cnpm install --save vue-router
配置路由文件,并在vue实例中导入:
import router from 'vue-router'
import HelloWorld from './components/HelloWorld'
// ...
Vue.use(router)
var rt = new router({
routes:[{
path: '/', //指定要跳转的路径
component: HelloWorld //指定要跳转的组件
}]
})
new Vue({
el: '#app',
router: router,
components: { App },
template: '<App/>'
})
设置视图(组件)加载的位置
<router-view></router-view>
路由跳转
<router-link to="/"></router-link>
<template>
<ul>
<li>
<router-link to="/helloworld">HELLO WORLD</router-link>
</li>
<li>
<router-link to="/helloearth">HELLO EARTH</router-link>
</li>
</ul>
</template>
路由参数传递
- 必须在路由内加入路由的name
- 必须在path后加
/:
加上传递的参数
路由:
const router = new VueRouter({
routes: [
{
name: "helloworld",
path: '/helloworld/:msg', // 指定跳转的路径和参数
component: HelloWorld, // 指定跳转的组件
// props: (route) => ({query: route.query.q})
}]
})
使用params在跳转链接带上参数:
<router-link
:to="{name: helloearth, params: {msg: '你好世界'}}">
HELLO WORLD
</router-link>
<!-- 传递:/helloworld/你好世界 -->
<!-- 接收:{{$route.params.msg}} -->
使用query在跳转链接带上参数:
<router-link
:to="{name: helloearth, query: {msg: '你好世界'}}">
HELLO WORLD
</router-link>
<!-- 传递:/helloworld?msg=你好世界 -->
<!-- 接收:可以创建一个函数返回 props,可将参数转换成另一种类型,将静态值与基于路由的值结合等等
const router = new VueRouter({
routes: [{
path: '/search',
component: SearchUser,
props: (route) => ({query: route.query.q })
}]
})
-->
网友评论