需求
在vue中,頁面的他跳轉和卡片切換一般會用到路由router,具體不多說,主要記錄一下路由的配置和幾種常用的跳轉方式
路由配置重定向 index.js :
import Home from '../components/Home'
import Page2 from '../components/Page2'
import Chil1 from '../components/Chil1'
import Chil2 from '../components/Chil2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home',
name: 'Home', //可以不用name字段 但有時需要用到name匹配
component: Home
} ,
{
path: '/page2',
name: 'Page2',
component: Page2,
children:[ //頁內切換卡片
{
path: '/chil1', // 帶‘/’ 表示根路徑
name: 'Chil1',
component: Chil1
},
{
path: 'chil2', // 不帶‘/’ 表示訪問路徑為/page2/chil2
name: 'Chil2',
component: Chil2
}
]
},
{
path: '/', //匹配根路徑 用於默認打開的頁面
name: 'index',
redirect: '/home' //redirect重定向到Home組件
}
]
})
路由跳轉的幾種方式
一、使用標簽路由 router-link
1、不傳參
<router-link :to="{name:'Home'}">
<router-link :to="{path:'/home'}">
2、傳參
<router-link :to="{name:'Home', params: {id:1}}">
<router-link :to="{path:'/home', params: {id:1}}">
// params傳參數
// 路由配置 path: "/home/:id"
// 不配置path ,第一次可請求,刷新頁面id會消失
// 配置path,刷新頁面id會保留
// html 取參 $route.params.id
// script 取參 this.$route.params.id
<router-link :to="{name:'Home', query: {id:1}}">
// query傳參數 (類似get,頁面url后面會顯示參數)
// 路由可不配置
// html 取參 $route.query.id
// script 取參 this.$route.query.id
二、編程式路由 this.$router.push()
1、不傳參
this.$router.push('/home')
this.$router.push({name:'Home'})
this.$router.push({path:'/home'})
2、傳參
this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name
// params傳參數
// 路由配置 path: "/home/:id"
// 不配置path ,第一次可請求,刷新頁面id會消失
// 配置path,刷新頁面id會保留
// html 取參 $route.params.id
// script 取參 this.$route.params.id
this.$router.push({name:'Home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
// query傳參數 (類似get,頁面url后面會顯示參數)
// 路由可不配置
// html 取參 $route.query.id
// script 取參 this.$route.query.id
在axios中使用 this.$router.push() 時,如果使用function會取不到this而報錯,而要使用箭頭函數
如下:
onSubmit() {
axios.post('http://localhost:8022/user/login',qs.stringify(this.user))
.then((response)=>{ //正確; 使用function(response){}會報錯。。。我也不知為啥。。
alert(response.data.msg);
if (response.data.url){
this.$router.push({path: '/home'})
}
})
.catch((error) => alert(error))
}
歡迎訪問個人博客:http://www.itle.info/