vue路由

2019-12-07  本文已影响0人  very_cute_girls

#安装

npm install vue-router --save

#创建router.js

import Vue from "vue";
import Router from "vue-router";

//1组件模块
import Lifi from "./components/Lifi.vue";
import Home from "./components/Home.vue";

Vue.use(Router);

export default new Router({
  routes: [
    { path: "/lifi", name: "Lifi", component: Lifi },
    { path: "/home", name: "Home", component: Home }
  ]
});

这里也可以另一种方式

 { path: "/text", name: "text", component:()=>import('../components/text') ,meta: { title: '测试' }}

#在main.js中引入router.js

import router from "./router";

#挂在到vue实例中

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

#给定组件显示的地方

<router-view></router-view>  //组件显示的地方

#使用

<router-link to="/home">主页</router-link>     //切换到指定的组件
<router-link to="/lifi">lifi</router-link>

#也可通过事件的方法来使用路由

methods:{
  toMain() {
    this.$router.push('./main');  //跳转到指定组件
  },
 
  //使用路由返回上一级
  goBack() {
    window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
  },
}

#设置默认路由

routes: [
    { path: '*', redirect: '/home' }
  ]

#动态路由方式传值

 { path: '/user/:id', component: User }

#这里记得to前面加冒号 :

<router-link :to="/content/123">{{key}}---{{item}}</router-link>

#获取路由传过来的值(传过来的是一个对象)

 this.$route.params

#get方式传值

 <router-link :to="'/pcontent/?id='+ index">{{index}}---{{item}}</router-link>

#获取传值(一样是对象)

this.$route.query

#编程式导航(几种方式)

this.$router.push({path:'main'});
or
this.$router.push('./main');
or
this.$router.push({name:'main'});
or
this.$router.push({name:'main',params:{id:123}});

#hash模式和history模式

默认是hash模式,如果想改为history模式,实例化router是加上mode
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

#路由嵌套

几个注意点,嵌套是在上一个路由里嵌套,并且path没有 " / "

routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
上一篇 下一篇

猜你喜欢

热点阅读