vue路由

vue路由使用

1.安裝vue路由vue

npm install vue-router

2.在src中新建router/index.js,引入vue路由vue-router

import Vue from 'vue'
import VueRouter from 'vue-router'//引入vue-router
Vue.use(VueRouter)

3.引入組件,並建立vue路由
*在這裏,可使用@進行引入,@至關於src目錄npm

import Home from "../components/Home";
import header from "../components/Header";
import List from "@/components/List";//@至關於src目錄
import footer from "../components/footer";
const routes=[
    {path:"/",component:Home},//默認頁
    {path:"/header",component:header},
    {path:"/List",component:List},
    {path:"/footer",component:footer},
]
export default new VueRouter({
    routes: routes,
    mode:"history" //去掉地址欄的#號
  })

4.在main.js中引入router/index.jsapp

import router from "@/router/index";

new Vue({
  el: '#app',
  router:router,
  components: { App },
  template: '<App/>'
})

5.路由跳轉this

<router-link to="/">首頁</router-link>
<router-view></router-view>

方法跳轉,在methods中定義一個方法,經過事件執行code

routerpush(){
            this.$router.push({ path: '/List' })//路由跳轉
            // this.$router.go(1);//在 history 記錄中向前或者後退多少步
            // this.$router.replace({ path: '/List' })//路由跳轉,但不會向history中添加記錄
        }

路由傳參

1.params傳參
路由配置component

{path:"/List",
name:"分類",
components:List
},

父組件中:經過路由屬性中的name來肯定匹配的路由,經過params來傳遞參數。router

this.$router.push({ name:"分類",params:{id:33} })

子組件中經過this.$route.params.id獲取參數
2.query傳參
路由配置事件

{path:"/List",
name:"分類",
components:List
},

父組件中:經過路由屬性中的name來肯定匹配的路由,經過query來傳遞參數。路由

this.$router.push({ name:"分類",query:{id:33} })

子組件中經過this.$route.query.id獲取參數

*區別:query是把參數放在地址欄上,刷新不會消失,params不會把參數放在地址上,刷新後消失

相關文章
相關標籤/搜索