基于Vue中的父子傳值問(wèn)題解決
主題是Vue中幾種常見(jiàn)的傳值方法。。。先寫個(gè)父子傳值吧
vue-cli構(gòu)建項(xiàng)目目錄,嚕啦啦,這個(gè)就不用說(shuō)了吧。
接著創(chuàng)建父子組件,父組件Father.vue,子組件Son.vue(隨意起名,開(kāi)心就好),然后在父組件中引入子組件,創(chuàng)建一個(gè)父組件的路由。車門已經(jīng)焊死了,請(qǐng)繼續(xù)往下看
1.父?jìng)髯?/b>
Father.vue(用v-bind(簡(jiǎn)寫 : ) 將父組件傳的值綁定到子組件上)
<template> <div> 我是爸爸:{{message}} <hr> <Son :toSonData='toSonData'></Son> </div></template> <script>import Son from './Son.vue';export default { data() { return { message : '兒子你好', toSonData: '大嘴巴子'//給子組件的值 }; }, components: { Son }};</script><style lang=’scss’ scoped></style>
Son.vue(在子組件中用props方法接收父組件傳來(lái)的值,兩種方法,具體用哪種看個(gè)人喜好,推薦第二種)
<template> <div> 我是兒子:{{message}} <br> 爸爸給我的禮物:{{toSonData}} </div></template> <script>export default { // props:['toSonData'],//第一種方式 props:{//第二種方式 toSonData:{ type:String, default:function(){ return '' } } }, data () { return { message : '爸爸你好' }; },} </script><style lang=’scss’ scoped></style>
效果圖:

2.子傳父
Son.vue(在子組件中創(chuàng)建一個(gè)按鈕,定義一個(gè)點(diǎn)擊事件,點(diǎn)擊事件里用this.$emit方法觸發(fā)一個(gè)自定義事件,并傳遞一個(gè)參數(shù))
<template> <div> 我是兒子:{{message}} <br> 爸爸給我的禮物:{{toSonData}} <br> <button @click='toFatherData'>給爸爸傳值</button> </div></template> <script>export default { // props:['toSonData'],//第一種方式 props:{//第二種方式 toSonData:{ type:String, default:function(){ return '' } } }, data () { return { message : '爸爸你好' }; }, methods:{ toFatherData(){ this.$emit('toFatherData','給爸爸的愛(ài)') } }} </script><style lang=’scss’ scoped></style>
Father.vue(在父組件中的子標(biāo)簽中監(jiān)聽(tīng)該自定義事件并添加一個(gè)響應(yīng)該事件的處理方法,將接收到的值賦給data中的sendSonMessage)
<template> <div> 我是爸爸:{{message}} <br> 兒子傳來(lái)的值:{{sendSonMessage}} <hr> <Son :toSonData='toSonData' @toFatherData='sendSonData'></Son> </div></template> <script>import Son from './Son.vue';export default { data() { return { message : '兒子你好', toSonData: '大嘴巴子',//給子組件的值 sendSonMessage: '' }; }, components: { Son }, methods:{ sendSonData(data){ this.sendSonMessage=data; } }};</script><style lang=’scss’ scoped></style>
效果圖:

補(bǔ)充知識(shí):在vue中的for循環(huán),我經(jīng)常用這兩種方法
1、
for(let item of response.data.result) {
用item操作每一條數(shù)據(jù)。 }
item:定義的每一條的變量
response.data.result:要循環(huán)的數(shù)組
2、
response.data.result.forEach((item, index) => {
用item操作每一條數(shù)據(jù)。})
response.data.result:要循環(huán)的數(shù)組
index:索引
以上這篇基于Vue中的父子傳值問(wèn)題解決就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. IntelliJ IDEA安裝插件的方法步驟3. 理解PHP5中static和const關(guān)鍵字4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. spring acegi security 1.0.0 發(fā)布6. MyBatis中的JdbcType映射使用詳解7. vue 使用localstorage實(shí)現(xiàn)面包屑的操作8. Python random庫(kù)使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備