【学记】vue-router

135 阅读2分钟

下载:npm i vue-router
注意:如果使用Vue2,建议使用4.0.0以下的版本,不然会有问题

下载指定版本:npm i vue-router@3.2.0

以Vue2为例

使用前的基本准备,第一步创建路由配置js文件,在src文件夹下创建router文件夹,文件夹内创建index.js,index.js简单编辑如下

//index.js

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

Vue.use(VueRouter);

export default new VueRouter({
    routes: [
      {
        path: "/main", //我的理解是路径和组件的对应关系可有看作一对key-value,通过路径访问对应组件
        name: "main", //name好比域名,router同样可以通过name来访问对应的组件
        component: ()=> import ("../pages/main/main"),
        children: [  //通过children配置子级路由
            {
                path: 'news',//此处一定不要写:/main/news,子路径会自动拿到上级的路径
                name: "news",
                component:()=> import ("../pages/main/News"),
            },
        ]
    },
    {
        path: "/another/:id/:title", //使用params传参时,path需要这样写,这里id,title会作为params对象里的key
        name: "another", 
        component: ()=> import ("../pages/main/another"),
        children: [ 
            ......
        ]
    }
  ]
})

第二部在main.js中加载vue-router

//main.js

import Vue from 'vue'
import router from "./router";

new Vue({
    router,
    ......
    render: h => h(App),
  }).$mount("#app");

然后就可以开始愉快的使用了,在App.vue使用<router-link><router-view>标签简单实现体验一下

//App.vue

<!--写完整的路径 -->
<router-link to="/pages/main/main">跳转</router-link>

<!--直接通过名字跳转 -->
<router-link :to="{name:'main'}">跳转</router-link>

<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link :to="`/main/news?id=${xx}&title=${xx}`">跳转</router-link>

<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="`/another/${xx}/${xx}`">跳转</router-link>

<!--跳转并携带query参数,to对象写法 -->
<router-link 
	:to="{             
                path:'/main',
		query:{
		   id:666,
                   title:'你好'
		}
	}"
>跳转</router-link>
				
<!-- 跳转并携带params参数,to的对象写法,通过名字跳转 -->
<router-link 
	:to="{
		name:'another',//注意!使用params时,这里不能用path
		params:{
		   id:666,
                    title:'你好'
		}
	}"
>跳转</router-link>

<!--显示对应组件-->
<router-view></router-view>

组件内获取参数
//main.vue
this.$route.query.id
this.$route.query.title

//another.vue
this.$route.params.id
this.$route.params.title

props可以直接将所有的参数传给对应组件的props

{
	name:'main',
	component:()=> import ("../pages/main/main"),

	//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
        // path:'/main',
	// props:{a:900}

	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
        // path:'/main/:id/:title',
	// props:true
	
	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
	path:'/main',
        props(route){
		return {
			id:route.query.id,
			title:route.query.title
		}
	}
}

<router-link>默认采用push方式来操作浏览器历史记录,如果要切换成replace,只需要给<router-link>加上replace属性即可

<router-link replace to="/pages/main/main">跳转</router-link>