-
安装路由
(2021.1.14)我的版本是 “vue-router”: "4.0.0-beta.6“ -
配置路由文件
在src文件夹下建立自己的vue-router文件
配置index.js文件
//此处引入的方法跟vue2不一样!!!!!!!!!
import { createWebHistory, createRouter } from 'vue-router'
const history = createWebHistory()
const router = createRouter({
history, // 路由模式
routes: [
{
path:'/',
redirect:'/home/homeson' // 重定向
},
{
// 页面逻辑
path: '/home',
name: 'home',
component: () => import('../view/home.vue'),//动态引入
children: [//嵌套一级子路由
{
path: "homeson",//子路由前不需要加斜杠 /
name: "homeson",
component: () => import('../view/main/homeSon.vue'),
props: true,
meta: { title: "首页" },
},
{
path: "article",
redirect:'/home/article/list', // 重定向
name: "article",
component: () => import('../view/main/article/article.vue'),
props: true,
meta: { title: "文章发布管理" },
children: [//嵌套二级子路由
{
path: "submit",
component: () => import('../view/main/article/submit.vue'),
// props: true,
// meta: { title: "首页" },
},
{
path: "list",
component: () => import('../view/main/article/list.vue'),
// props: true,
// meta: { title: "首页" },
},
]
}
]
})
export default router
- 在main.js中配置路由
//1.导入
import { createApp } from "vue";
import App from "./App.vue";
import router from "./route/index.js";
//2.路由发生变化修改页面title
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title;
}
next();
});
//全局注入
const app = createApp(App);
components.forEach((component) => {
app.component(component.name, component);
});
app.use(router);
app.mount("#app");
- 路由传参
//传参页面
<script>
import { getCurrentInstance, reactive, ref} from "vue";
export default {
setup() {
const { ctx } = getCurrentInstance();//相当于this
function goPage() {
ctx.$router.push({
path:'/接收参数页面',
query: { id:要传递的参数 }
})
}
return {}
},
}
</script>
//接收页面
<script>
import { getCurrentInstance, reactive, ref} from "vue";
import { useRoute} from 'vue-router'//引入方法
export default {
setup() {
const route=useRoute();//如同v2的$route 获取路由传参用的
const id=ref("")
function getFn(){
id=route.query.id;
}
return {id}
},
}
</script>
**
有用的话记得点个赞哦0.0
**