通過VueRouter來實作元件之間的跳轉:參數的傳遞,具體内容如下
login ---使用者名--->main
①明确發送方和接收方
②配置接收方的路由位址
{path:'/myTest',component:TestComponent}
-->
{path:'/myTest/:id',component:TestComponent}
③接收方擷取傳遞來的資料
this.$route.params.id
④跳轉的時候,發送參數
this.$router.push('/myTest/20')
跳轉
代碼:
傳參
{{msg}}
//建立首頁面元件
var myMain = Vue.component("main-component",{
//儲存登入傳遞過來的資料
data:function(){
return {
uName:''
}
},
template:`
首頁面使用者名:{{uName}}
`,
//挂載該元件時自動拿到資料
beforeMount:function(){
//接收參數
console.log(this.$route.params);
this.uName = this.$route.params.myName ;
}
})
//建立登入頁面元件
var myLogin = Vue.component("login-component",{
//儲存使用者輸入的資料
data:function(){
return {
userInput:""
}
},
methods:{
toMain:function(){
//跳轉到首頁面,并将使用者輸入的名字發送過去
this.$router.push("/main/"+this.userInput);
console.log(this.userInput);
}
},
template:`
登入頁面
登入到首頁面
登入到首頁面
`
})
var NotFound = Vue.component("not-found",{
template:`
404 Page Not Found
傳回登入頁
`
})
//配置路由詞典
const myRoutes = [
{path:"",component:myLogin},
{path:"/login",component:myLogin},
//注意冒号,不用/否則會當成位址
{path:"/main/:myName",component:myMain},
//沒有比對到任何頁面則跳轉到notfound頁面
{path:"*",component:NotFound}
]
const myRouter = new VueRouter({
routes:myRoutes
})
new Vue({
router:myRouter,
el:"#container",
data:{
msg:"Hello VueJs"
}
})
// 注意,路由位址
傳參練習
{{msg}}
//建立産品清單元件
var myList = Vue.component("product-list",{
//儲存産品清單的資料
data:function(){
return{
productList:["蘋果","華為","三星","小米","vivo"]
}
},
template:`
這是清單頁
-
//将index傳遞過去
{{tmp}}
`
})
//詳情頁元件
var myDetail = Vue.component("product-detail",{
//儲存傳遞過來的index
data:function(){
return{
myIndex:""
}
},
//在挂載完成後,将接收到的index指派給myIndex
mounted:function(){
this.myIndex = this.$route.params.id;
},
template:`
這是詳情頁
這是id為:{{myIndex}}的産品
`
})
//頁面找不到的時候
var NotFound = Vue.component("not-found",{
template:`
404 Page Not Found
`
})
// 配置路由詞典
const myRoutes = [
{path:"",component:myList},
{path:"/list",component:myList},
{path:"/detail/:id",component:myDetail},
{path:"*",component:NotFound},
]
const myRouter = new VueRouter({
routes:myRoutes
})
new Vue({
router:myRouter,
el:"#container",
data:{
msg:"Hello VueJs"
}
})
關于vue.js的學習教程,請大家點選專題vue.js元件學習教程、Vue.js前端元件學習教程進行學習。
以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。