注意vue-router版本,我用的是"vue-router": "^4.0.0-alpha.6"
官网的使用步骤
const Home
= { template
: '<div>Home</div>' }
const About
= { template
: '<div>About</div>' }
const routes
= [
{ path
: '/', component
: Home
},
{ path
: '/about', component
: About
},
]
const router
= VueRouter
.createRouter({
history
: VueRouter
.createWebHashHistory(),
routes
,
})
const app
= Vue
.createApp({})
app
.use(router
)
app
.mount('#app')
自己来配
定义router.js
import { createRouter
, createWebHashHistory
} from "vue-router";
import Home
from "../views/Home.vue";
const routes
= [
{
path
: "/home",
name
: "Home",
component
: Home
,
},
{
path
: "/test",
name
: "Test",
component
: () =>
import( "../views/Test.vue"),
},
];
const router
= createRouter({
history
: createWebHashHistory(),
routes
,
});
export default router
;
main.js入口文件引入
import { createApp
} from "vue";
import App
from "./App.vue";
import router
from "./router/index";
import "./index.css";
const app
= createApp(App
);
app
.use(router
);
app
.mount("#app");
使用
<template>
<div>
<router-link to="/home">Home
</router-link>
<router-link to='/test'>Test
</router-link>
</div>
<router-view></router-view>
</template>
<script>
import { onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
export default {
setup(props, context) {
onMounted(() => {
console.log(route);
console.log(router);
});
const route = useRoute();
const router = useRouter();
return {};
},
};
</script>
这样就可以像以前那样用路由了
有一个小细节
{
path
: "/:home(\\d+)",
name
: "Home",
alias
: "/home",
component
: Home
,
},
别名alias 正则 别名alias数组
详细了解可以看文档vue-router
转载请注明原文地址: https://lol.8miu.com/read-31185.html