API
1,to
表示目标路由的链接。当被点击后,内部会立刻把 to 的值传到 router.push(),所以这个值可以是一个字符串或者是描述目标位置的对象。
2,replace
设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。
<router-link :to="{ path: '/abc'}" replace></router-link>
3,tag
有时候想要 渲染成某种标签,例如
- 。 于是我们使用 tag prop 类指定何种标签,同样它还是会监听点击,触发导航。
-
<router-link to="/foo" tag="li">foo</router-link> <!-- 渲染结果 --> <li>foo</li>
嵌套路由
URL 中各段动态路径也按某种结构对应嵌套的各层组件
我的项目是APP.vue套着Home.vue套着News.vue
代码
首先修改router下的index
编程式路由导航
<template> <div > <!-- 编程式导航 --> <!-- 想要导航到不同的 URL,则使用 router.push 方法。 这个方法会向 history 栈添加一个新的记录,所以, 当用户点击浏览器后退按钮时,则回到之前的 URL。 --> <button @click="push()" >push</button> <!-- 跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录, 而是跟它的方法名一样 —— 替换掉当前的 history 记录。 --> <button @click="replace()" >replace</button> <button @click="$router.back()" >回退</button> <button @click="$router.go(1)" >在浏览器记录中前进一步</button> <button @click="$router.go(-1)" >在浏览器记录中后退一步</button> </div> </template> <script> export default{ methods: { push(){ this.$router.push('/demo') }, replace(){ this.$router.replace('/demo') } }, } </script>
vue-router重定向
有时候,配置不同的路由,但是,希望跳转到同一个页面,这个时候就需要使用redirect进行重定向,这样,就可以跳转到同一个页面。
export default new Router({ routes: [ { path: '/', component: Hello }, { path:'/goback', redirect:'/' } ] })
vue-router别名
“重定向”的意思是,当用户访问 /a时,URL 将会被替换成 /b,然后匹配路由为 /b,那么“别名”又是什么呢?
/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。
{ path: '/about', name: 'About', alias:'/demo', // 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') },
当你访问demo时,页面是about
VueRouter路由组件传参
props是用于父组件向子组件传递数据信息(props是单向绑定的,即只能父组件向子组件传递,不能反向.)
代码:父组件<!-- 父组件 --> <template> <div> <h1>我是父组件!</h1> <child message="我是子组件一!"></child> <!-- 这是一个 JavaScript 表达式而不是一个字符串。--> <child v-bind:message="a+b"></child> <!-- 用一个变量进行动态赋值。--> <child v-bind:message="msg"></child> </div> </template> <script> import child from '../components/child.vue' export default { components: {child}, data() { return { a:'我是子组件二!', b:112233, msg: '我是子组件三!'+ Math.random() } } } </script>
子组件
<!-- 子组件 --> <template> <h3>{{message}}</h3> </template> <script> export default { props: ['message'] } </script>
通过$emit 实现子组件向父组件通信
父组件<template> <div> <h1>{{title}}</h1> <child @Message="showMsg"></child> </div> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, data(){ return{ title:'' } }, methods:{ showMsg(title){ this.title=title; } } } </script>
子组件
<template> <div> <h3>我是子组件</h3> </div> </template> <script> export default { mounted:function (){ this.$emit('Message','我是父组价') } } </script>