vue-router簡單配置 --------- 系列一

準備工作

前提安裝了node,webpack中配置完成了vue環境,

  • 1.安裝npm instal vue-router
  • 2.建立pages文件下 cinema/index.vue 文件
    mine/index.vue 文件以及movie/index.vue 文件
    附上cinema/index.vue中內容 另外兩個同(將對應文件中修改成相應文件夾名,方便區別頁面中顯示,也可以不要,不要的話下面的配置也不用寫)
    cinema/index.vue
<template>
    <div>
        <h2>cinema</h2>
    </div>
</template>

<script>
export default {
    
}
</script>

<style>
</style>
  • 創建router/index.js
    整個文件夾以及文件的分佈情況如下圖
    在這裏插入圖片描述

開始配置

1. router/index.js 對router 中的index.js文件 進行配置,相應配置步驟寫的很詳細

import Vue from "vue";
import VueRouter from "vue-router" //1安裝完路由要進行引入
import Movie from "../pages/movie"//引入Movie組件 供routes中組件compontent使用 下兩個同
import Cinema from "../pages/cinema"
import Mine from "../pages/mine"

Vue.use(VueRouter)//2 使用VueRouter

//3 路由的配置
const router = new VueRouter({
    // 第5步進行完成後,開始路由配置
    //6.1配置路由
    mode:"hash",//6.2配置mode
    /**mode 的方式有兩種,
     * 一種是hash 哈希值 路由身上帶#,
     * 另外一種是history ,路由身上沒有#,使用history的話,必須要和後端一起做配置,否則只有第一次能被找到,操作的時候會返回404 找不到
    */
    routes:[//6.3 路由配置的規則routes 是一個數組,數組裏放的是對象,一個對象代表一個路由的配置
        /**
         * path: 代表配置的路由地址
         * component: 當用戶請求的路由與path相對應後渲染的組件
         */
        {
            path:"/movie",//6.4 
            component:Movie//6.5Movie 需要先引入後使用
            //7 配置完成後去App.vue中使用內置組件router-view進行顯示
        },
        {
            path:"/cinema",
            component:Cinema
        },
        {
            path:"/mine",
            component:Mine
        }
    ]
})

export default router;//4 導出路由 小坑:名字只能是router
//導出後在 入口文件中使用src下的index.js中使用 並注入vue

2. src/index 在src中的index.js中進行引入,並注入到創建的實例vue身上

import Vue from "vue";
import App from "./App";
import router from "./router"//5使用router 
new Vue({
    router,//5.1 注入vue實例  !!!很重要
    render:h=>h(App)
}).$mount("#app")

3.src/app.vue中使用<router-view></router-view>進行接受顯示

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name:"App",
    
  };
</script>

<style>

</style>

顯示效果

第一步 在控制檯 npm run dev 運行程序

  • 9002,是我在webpack中設置的端口號是9002
  • /#/是因爲在路由配置中使用的mode是hash 使用history的話沒有# 但需要後端渲染
    在這裏插入圖片描述
    第二步
    在地址欄添加movie 頁面將會頁面上將會顯示movie
    頁面上成功顯示內容
    在這裏插入圖片描述

擴展

router-view :使用了路由後,當路由的path匹配成功後,在router-view可以將你需要的組件掛載到頁面上。

路由跳轉的方式

  • 1、a標籤 類似html中的錨點
  • 2、router-link router–link 也是一個內置組件,用來做路由跳轉,裏面有兩個屬性,一個是to 一個是tag
    • to ,to屬性類似a上的href
    • tag 可以指定當前組件渲染的時候,渲染到哪個元素上
  • 3、 編程式導航: js代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章