Vue-Router路由学习

目录文件:

 

main.js文件

// 从vue中导入创建app方法
import { createApp } from 'vue'
import App from './App.vue'

// vue-router导入创建路由方法
import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'

import HomePage from './pages/HomePage.vue'
import ArticleListPage from './pages/ArticleListPage.vue'
import SearchPage from './pages/SearchPage.vue'


//创建路由集,路由配置
// path路由跳转位置,conponent对应组件
const routes =[
{
path:"/",
component:HomePage,
},
{
path:"/article-list",
component: ArticleListPage,
},
{
path:"/search",
component: SearchPage,


}
]

//使用导入的createRouter方法,创建一个router,router负责管理路由
const router = createRouter({
//history对象,就是浏览器访问的URL,
// createWebHashHistory路由模式路径带#号,而createWebHistory不带#号
history:createWebHistory(),
//前面的routes是路由集锁定位置,后面的routes是路由数组
routes:routes,

})

//createApp(App).mount('#app')
//创建app,使用路由
createApp(App).use(router).mount("#app")

 

app.vue

<script setup>
//导入
import HelloWorld from './components/HelloWorld.vue'
import HomePage from './pages/HomePage.vue'
</script>

<template>

<div id="div1">
<h1>News Demo</h1>

<div id="nav">
<!-- 路由到当前页面 -->
<router-link to="/">Home</router-link>
<!-- 路由到某个页面 -->
<router-link to="/article-list">Article List</router-link>
<router-link to="/search">Search</router-link>
</div>
<div id="container">
<!-- routrt-view替代a标签,但又有不同,router-view在当前页面跳转,a标签在其他页面跳转 -->
<!-- 切换不同的组件显示不同的内容,地址同样会改变 -->
<!-- 路由组件渲染部分,就是点击那部分路由就在这显示 -->
<router-view></router-view>
</div>

<div id="footer">
<hr />
<p>Copyright &copy; Justin 2022-2023</p>
</div>


</div>

</template>

 

<style>
#div1 {
width: 600px;
margin: 0 auto;
}

/* CSS */
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}

#container {
text-align: left;
}

#container h2 {
text-align: center;
}

#nav a {
display: inline-block;
border: 1px solid #ccc;
width: 120px;
height: 30px;
line-height: 30px;
margin: 0 20px;
text-decoration: none;
color: #337ab7;
}

#nav a:hover {
background-color: #337ab7;
color: white;
}
</style>

posted @ 2022-04-02 11:13  Leisure623  阅读(64)  评论(0编辑  收藏  举报