this.$router 和 this.$route
- this.$router 用來操作路由比如 push
- this.$route 用來獲取路由資訊比如
this.$route.name // 路由名稱
this.$route.Path // 不帶引數路徑
this.$route.fullPath // 完整路徑
this.$route.query // query引數
this.$route.params // params引數
複製程式碼
路由傳參(宣告式)
html
<!--name為路由裡面的名字也可以寫為**path** -->
<router-link to="{path: `/path/${id}`}">路徑拼接資料</router-link>
<router-link :to="{ name: 'query', query: { id: 1 }}">query資料</router-link>
<router-link :to="{ name:'params',params:{name:'abc'}}">params資料</router-link>
<router-view></router-view>
複製程式碼
js
routes: [
{
name: "path",
path: "/path/:id",
component: Path
},
{
name: "query",
path: "/query",
component: Query
},
{
// 測試發現'/:id'可以省略,加上了之後跟路由拼接效果一致
name: "params",
path: "/params",
component: Params
}
]
複製程式碼
獲取引數
console.log(this.$route.params);
console.log(this.$route.query);
console.log(this.$route.params);
複製程式碼
1.路徑拼接
2.query 3.params路由傳參(程式設計式)
html
<span @click="clickPath">路徑拼接資料</span>
<span @click="clickQuery">query資料</span>
<span @click="clickParms">params資料</span>
<router-view></router-view>
複製程式碼
路由和methods
methods: {
clickPath (id) {
this.$router.push(`/path/${id}`);
},
clickQuery() {
this.$router.push({ name: "query", query: { id: 1 } });
},
clickParms() {
this.$router.push({ name: "params", params: { name: 'abc' } });
}
},
routes: [
{
name: "path",
path: "/path/:id",
component: Path
},
{
name: "query",
path: "/query",
component: Query
},
{
// 測試發現'/:id'可以省略,加上了之後跟路由拼接效果一致
name: "params",
path: "/params",
component: Params
}
]
複製程式碼
獲取引數
console.log(this.$route.params);
console.log(this.$route.query);
console.log(this.$route.params);
複製程式碼