1,使用路由前先在项目中安装路由,命令:npm i vue-router
2,在模块中使用
import Vue from "vue"
import VueRouter from "vue-router" // 引入依赖中的vue和vue-router
Vue.use(VueRouter); //模块中安装路由功能
3,创建路由对象并导出
var router = new VueRouter(Config);
export default router;
4,注入到vue中 ,可以在任何组件内通过 this.$router
访问路由器,也可以通过 this.$route
访问当前路由:
import router from "./routes";//此路径为上面的配置路由模块
new Vue({
render: h => h(App),
router,//配置路由到VUE中,在整个应用中都有路由功能
}).$mount('#app')
5,现在就可以定义路由跳转了
export default{
routes:[
{
path:"/",
name:"Home",
component:()=>import("@/views/Home")
},
{
path:"/user/:id",
name:"User",
component:()=>import("@/views/ChannelNews")
},
{
path:"*",//通配符,匹配所有路径
name:"404",
component:()=>import("@/views/NotFound")
}
],
mode: "history",
// 路由模式:
// hash:路径来自于地址栏中#后面的值,这种模式兼容性比较
// history:路径来自于真实的地址路径,旧浏览器不兼容
// abstract:路径来自于内存
};
6,路由跳转
<router-link :to="{name:'User', params: {id:1}}">
<router-link :to="{name:'User', query: {id:1}}">,
或者在js里
this.$router.push({name:'User',query: {id:'1'}})
this.$router.push({path:'/user',query: {id:'1'}})
this.$router.push({name:'User',params: {id:'1'}}) // 只能用 name
// params传参数 (类似post),uery传参数 (类似get,url后面会显示参数)
7,读取参数
在html 中取参 $route.params.id或$route.query.id
在script 中取参 this.$route.params.id或this.$route.query.id
好啦,今天先写到这里,如有需要的评论一下,后面会补充,谢谢!