Vue 組件傳值幾種常用方法【總結(jié)】
使用vue也有很多年了,一直都沒(méi)有整理一下相關(guān)知識(shí),給大家總結(jié)下開(kāi)發(fā)過(guò)程中所遇到的一些坑,主要給大家總結(jié)一下vue組件傳值的幾種常用方法:
1、通過(guò)路由帶參數(shù)傳值
① A組件通過(guò)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、子組件向父組件傳值
子組件主要通過(guò)事件向父組件傳遞數(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ì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
十分鐘帶你快速上手Vue3過(guò)渡動(dòng)畫(huà)
在開(kāi)發(fā)中我們想要給一個(gè)組件的顯示和消失添加某種過(guò)渡動(dòng)畫(huà),可以很好的增加用戶(hù)體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于如何快速上手Vue3過(guò)渡動(dòng)畫(huà)的相關(guān)資料,需要的朋友可以參考下2022-02-02
總結(jié)4個(gè)方面優(yōu)化Vue項(xiàng)目
在本篇文章里我們給大家整理了一篇關(guān)于優(yōu)化VUE項(xiàng)目的四個(gè)總要點(diǎn),對(duì)此有需要的朋友們學(xué)習(xí)下天。2019-02-02
VuePress在build打包時(shí)window?document?is?not?defined問(wèn)題解決
這篇文章主要為大家介紹了VuePress在build打包時(shí)window?document?is?not?defined問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
vue+Element實(shí)現(xiàn)搜索關(guān)鍵字高亮功能
這篇文章主要為大家詳細(xì)介紹了vue+Element實(shí)現(xiàn)搜索關(guān)鍵字高亮功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
Element中el-table動(dòng)態(tài)合并單元格(span-method方法)
本文主要介紹了Element中el-table動(dòng)態(tài)合并單元格(span-method方法),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Vue?export?default中的name屬性有哪些作用
這篇文章主要介紹了Vue?export?default中的name屬性有哪些作用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Vue.js@2.6.10更新內(nèi)置錯(cuò)誤處機(jī)制Fundebug同步支持相應(yīng)錯(cuò)誤監(jiān)控
這篇文章主要介紹了Vue.js@2.6.10更新內(nèi)置錯(cuò)誤處機(jī)制,F(xiàn)undebug同步支持相應(yīng)錯(cuò)誤監(jiān)控 ,需要的朋友可以參考下2019-05-05
Vue axios 跨域請(qǐng)求無(wú)法帶上cookie的解決
這篇文章主要介紹了Vue axios 跨域請(qǐng)求無(wú)法帶上cookie的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09

