Vue3.0使用路由vue-router,巢狀子路由、修改頁面title及其路由傳參等等
阿新 • • 發佈:2021-01-25
-
安裝路由
(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
**