既然用了vue,那麼vue-router就是在項目開發中必不可少的一部分操作了,這裏我特意整理了一些在vue項目開發過程中涉及到的一些操作吧。
一、路由之間傳參
由A路由到B路由之間的傳參,可以通過$router的query和param傳遞,用query傳遞的參數,會在瀏覽器的url路徑中展示出來,不具有保密性,但是刷新後依舊存在,由param傳遞的參數,不會在瀏覽器的url路徑中展示出來,而且刷新後不會再在當前頁面中展示,具體使用方法如下:
this.$router.push({
path: "/imp/style",
query:"params"
})
this.$router.push({
path: "/imp/style",
query:{key:value}
})
this.$router.push({
path: "/imp/style",
param:{key:value}
})
this.$router.push({
path: "/imp/style",
param:"params"
})
取值方法:
query:
this.$route.query
param:
this.$route.param
二、父子組件之間傳參
父組件
先在父組件中引入子組件,
import childToP from './childToP'
然後在tempate裏面使用
<div class="context">
<div>這是父組件
<p>{{message}}</p></div>
<childToP @childData="getData"></childToP>
</div>
定義一個@childData="getData"方法,接收子組件傳遞給父組件的事件,@childData這個方法是子組件裏定義的。
methods: {
getData(getVal) {
// getVal就是子組件的操作事件傳過來的值
this.message = getVal;
},
},
父組件向子組件傳參
如果需要從父組件裏向子組件傳遞信息或者點擊事件,可以在使用子組件的時候,在子組件上綁定屬性和要傳遞的事件,要先在data裏面聲明該屬性,即:pdata,然後在子組件裏面使用props來接收,
import toC from './toC'
<to-C :msgFromP="pdata" :aaa="func"></to-C>
<template>
<div class="context">
this is aaa
<to-C :msgFromP="pdata" :aaa="func"></to-C>
</div>
</template>
<script>
import toC from './toC'
export default {
components: {toC},
name: "parentToC",
data() {
return {
pdata: 'this is parent message'
}
},
methods: {
//這裏是在父組件定義的方法,在子組件裏面也可以接收,然後通過對子組件的操作實現你的目的
func() {
console.log('ccc');
}
}
}
</script>
在子組件裏面接收
<template>
<div class="context222">
<p class="text" @click="aaa">{{msgFromP}}</p>
</div>
</template>
<script>
export default {
name: "toC",
props: {
msgFromP: '',
aaa: null
}
}
子組件
在子組件中,可以直接在div裏寫你要傳遞的信息,不需要使用 this.$emit() 方法也可;
<template>
<div class="context">
<div>{{msg1}}</div>
</div>
</template>
<script>
export default {
name: "childToP",
data() {
return {
msg1:'這是子組件這是子組件這是子組件',
}
}
}
</script>
子組件向父組件傳參
如果你需要操作父組件裏面的數據或者給父組件發信息,先定義一個點擊事件,然後用 this.$emit("childData", this.msg) 方法,把子組件裏要傳遞的信息發送過去即可。
<template>
<div class="context">
<div @click="tomsg">這是子組件</div>
</div>
</template>
<script>
export default {
name: "childToP",
data(){
return{
msg:"this is child data"
}
},
methods:{
tomsg(){
// 這裏也可以是對象
let data="這是子組件裏面的數據"
this.msg=data
this.$emit("childData",this.msg)
}
}
}
</script>