Vue 組件傳值幾種常用方法【總結(jié)】
使用vue也有很多年了,一直都沒有整理一下相關(guān)知識(shí),給大家總結(jié)下開發(fā)過程中所遇到的一些坑,主要給大家總結(jié)一下vue組件傳值的幾種常用方法:
1、通過路由帶參數(shù)傳值
① A組件通過query把id傳給B組件
this.$router.push({path:'/B',query:{id:1}})
② B組件接收
this.$route.query.id
2、父組件向子組件傳值
使用props向子組件傳遞數(shù)據(jù)
子組件部分:child.vue
<template>
<div>
<ul>
<li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li>
</ul>
</div>
</template>
<script>
export default {
props:['nameList']
}
</script>
父組件部分:
<template>
<div>
<div>這是父組件</div>
<child :name-list='names'></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
components:{
child
},
data(){
return{
names:[
{name:'柯南'},
{name:'小蘭'},
{name:'工藤新一'}
]
}
}
}
</script>
3、子組件向父組件傳值
子組件主要通過事件向父組件傳遞數(shù)據(jù):
子組件部分:
<template>
<div>
<ul>
<li v-for='(item,index) in nameList' :key='index'>{{item.name}}</li>
</ul>
<Button @click='toParent'>點(diǎn)擊我</Button>
</div>
</template>
<script>
export default {
props:['nameList'],
methods:{
toParent(){
this.$emit('emitData',123)
}
}
}
</script>
父組件部分:
<template>
<div>
<div>這是父組件</div>
<child :name-list='names' @emitData='getData'></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
components:{
child
},
data(){
return{
names:[
{name:'柯南'},
{name:'小蘭'},
{name:'工藤新一'}
]
}
},
methods:{
getData(data){
console.log(data); //123
}
}
}
</script>
總結(jié)
以上所述是小編給大家介紹的Vue 組件傳值幾種常用方法【總結(jié)】,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue中使用ElementUI使用第三方圖標(biāo)庫iconfont的示例
這篇文章主要介紹了Vue中使用ElementUI使用第三方圖標(biāo)庫iconfont的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10
關(guān)于怎么在vue項(xiàng)目里寫react詳情
本篇文章是在vue項(xiàng)目里寫tsx的一篇介紹。其實(shí)vue里面寫jsx也挺有意思的,接下來小編九給大家詳細(xì)介紹吧,感興趣的小伙伴請(qǐng)參考下面的文章內(nèi)容2021-09-09
Vue 用Vant實(shí)現(xiàn)時(shí)間選擇器的示例代碼
這篇文章主要介紹了Vue 用Vant實(shí)現(xiàn)時(shí)間選擇器的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Vue中的函數(shù)同步執(zhí)行導(dǎo)致的數(shù)據(jù)獲取失敗問題處理辦法
Vue中的mount中有兩個(gè)函數(shù),第一個(gè)函數(shù)執(zhí)行完后給data中的userInfo賦值,但是第二個(gè)函數(shù)獲取userInfo時(shí)是空值,這種情況可能是因?yàn)榈诙€(gè)函數(shù)在獲取 userInfo 時(shí)發(fā)生在第一個(gè)函數(shù)執(zhí)行完之前,所以本文給大家介紹了Vue中的函數(shù)同步執(zhí)行導(dǎo)致的數(shù)據(jù)獲取失敗問題處理辦法2024-08-08
vue?點(diǎn)擊按鈕?路由跳轉(zhuǎn)指定頁面的實(shí)現(xiàn)方式
這篇文章主要介紹了vue?點(diǎn)擊按鈕?路由跳轉(zhuǎn)指定頁面的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯(cuò)誤原因以及修復(fù)方式
本文主要介紹了Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯(cuò)誤原因以及修復(fù)方式,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Vue 2.0+Vue-router構(gòu)建一個(gè)簡單的單頁應(yīng)用(附源碼)
這篇文章主要給大家介紹了基于Vue 2.0+Vue-router構(gòu)建了一個(gè)簡單的單頁應(yīng)用,文中通過實(shí)例介紹的非常詳細(xì),并在文末給出了源碼下載,需要的朋友可以下載學(xué)習(xí)參考,下面來一起看看吧。2017-03-03

