一、父組件向子組件傳值
通過props來實作,子組件通過props來接收父組件傳過來的值!
1、邏輯梳理
父組件中:
第一步:引入子組件;
import sonShow from '../../component/son.vue';
第二步:在components中對子組件進行注冊;
components: {
sonShow
},
第三步:以標簽的形式載入;通過資料系結的形式進行傳值~
<son-show :reciveUserInfo="userInfo"></son-show>
子組件中:
通過props接收父組件中傳過來的值;
props:["reciveUserInfo"],
2、代碼展示
父組件index.vue
<template>
<view >
<son-show :reciveUserInfo="userInfo"></son-show>
</view>
</template>
<script>
import sonShow from '../../component/son.vue';
export default {
components: {
sonShow
},
data() {
return {
userInfo: [{
"userName": "kaliwo",
"age": "19"
},
{
"userName": "lihuahua",
"age": "39"
}
]
}
}
}
</script>
子組件son.vue
<template>
<view >
<block v-for="(item,index) in reciveUserInfo" :key="index">
<view >
<text>{{item.userName}}</text>
<text>{{item.age}}</text>
</view>
</block>
</view>
</template>
<script>
export default{
props:["reciveUserInfo"],
}
</script>
<style>
.mesg{
display: flex;
flex-direction: column;
align-items: center;
}
</style>
3、結果

四、說明
對于一些詳情頁,比如有時我們需要點贊數量+1,-1的效果;但是,由于子組件不能改變父組件的值,所以直接操作從父組件接收的值進行更改是沒有效果的!就像如下:
let list = that.reciveUserInfo;
for(var i in list){
let tempAge = list[i].age + 1;
list[i].age = tempAge;
that.reciveUserInfo = list;
}
年齡還是沒有改變,所以應該怎么做了?
把從父組件接收到的值reciveUserInfo賦給一個新的變數mesgShow,對這個新的變數進行操作,然后用對齊進行渲染即可!
let list = that.reciveUserInfo;
for(var i in list){
let tempAge = list[i].age + 1;
list[i].age = tempAge;
that.mesgShow = list;
}
此時的結果為:age+1

附加:改變的代碼:

二、子組件向父組件傳值
與微信小程式自定義組件中子組件向父組件傳值一樣的邏輯,都是通過事件,下面直接上代碼:
父組件index.vue
<template>
<view >
<son-show @send="getSonValue"></son-show>
</view>
</template>
<script>
import sonShow from '../../component/son.vue';
export default {
components: {
sonShow
},
methods:{
getSonValue: function(res){
console.log("res=========",res)
}
}
}
</script>
子組件;
<template>
<view @click="sendMegToIndex">
點我向父組件傳值
</view>
</template>
<script>
export default{
methods:{
sendMegToIndex: function(){
// 向父組件傳值
this.$emit("send","我來自子組件")
}
}
}
</script>
最終結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/229749.html
標籤:其他
上一篇:零基礎怎么學習前端
