037、Vue3+TypeScript基礎,使用router.push進行導航式路由跳轉

像一棵海草海草海草發表於2024-08-20

01、main.js程式碼如下:

// 引入createApp用於建立Vue例項
import {createApp} from 'vue'
// 引入App.vue根元件
import App from './App.vue'

//引入路由
import router from './router'

const app = createApp(App);
//使用路由
app.use(router);
// App.vue的根元素id為app
app.mount('#app')

02、index.ts程式碼如下:

//建立路由並暴露出去
import {createRouter, createWebHistory} from 'vue-router'
import Home from '@/view/Home.vue'
import About from '@/view/About.vue'
import News from '@/view/News.vue'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {name: 'myHome', path: '/home', component: Home},
        {name: 'myAbout', path: '/about', component: About},
        {name: 'myNews', path: '/news', component: News},
    ]
})

export default router

03、App.vue程式碼如下:

<template>
  <div class="app">
    <h2 class="title">App.Vue路由測試</h2>
    <!-- 導航區-->
    <div class="navigate">
      <router-link to="/Home" class="nav-button">首頁</router-link>
      <router-link :to="{name:'myNews'}" class="nav-button">新聞</router-link>
      <router-link :to="{path:'/about'}" class="nav-button">關於</router-link>
      <button @click="jmp">跳轉</button>
    </div>

    <!-- 內容區-->
    <div class="mai-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
// 介面會根據當前路由的變化,在RouterView所在的位置渲染不同的元件
import {RouterView} from 'vue-router'
import router from "@/router";

function jmp() {
  router.push('/News')
}

</script>

<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}

.nav-button {
  display: inline-block; /* 讓連結顯示為塊級元素,以便應用寬度和高度 */
  padding: 10px 20px; /* 內邊距 */
  margin: 0 5px; /* 外邊距,用於按鈕之間的間隔 */
  text-decoration: none; /* 移除下劃線 */
  color: white; /* 文字顏色 */
  background-color: #007bff; /* 背景顏色 */
  border-radius: 5px; /* 邊框圓角 */
  transition: background-color 0.3s; /* 平滑過渡效果 */
}

.nav-button:hover {
  background-color: #0056b3; /* 滑鼠懸停時的背景顏色 */
}

.nav-button.router-link-active {
  background-color: #28a745; /* 當前啟用(路由匹配)時的背景顏色 */
}

.mai-content {
  /* 新增邊框樣式 */
  border: 2px solid #000; /* 邊框寬度、樣式和顏色 */
  border-radius: 5px; /* 可選:新增邊框圓角 */
  padding: 20px; /* 可選:給內部內容新增一些內邊距 */
  margin: 20px; /* 可選:給元素新增一些外邊距,以便與其他元素隔開 */
}
</style>

04、About.vue程式碼如下:

<template>
  <div class="about">
    <h2>我是About頁面</h2>
  </div>
</template>

<script setup lang="ts" name="about">
</script>

<style scoped>
</style>

05、Home.vue程式碼如下:

<template>
  <div class="home">
    <h2>我是Home頁面</h2>
  </div>
</template>

<script setup lang="ts" name="home">
</script>

<style scoped>
</style>

06、New.vue程式碼如下:

<template>
  <div class="news">
    <h2>我是News頁面</h2>
  </div>
</template>

<script setup lang="ts">
</script>

<style scoped>
</style>

07、瀏覽器效果如下:

相關文章