1、父組件向子組件傳值css
經過props來實現,子組件經過props來接收父組件傳過來的值!vue
一、邏輯梳理小程序
第一步:引入子組件;微信小程序
import sonShow from '../../component/son.vue';
第二步:在components中對子組件進行註冊;微信
components: { sonShow },
第三步:以標籤的形式載入;經過數據綁定的形式進行傳值~flex
<son-show :reciveUserInfo="userInfo"></son-show>
經過props接收父組件中傳過來的值;this
props:["reciveUserInfo"],
二、代碼展現spa
父組件index.vuecomponent
<template> <view class="content"> <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.vueblog
<template> <view class=""> <block v-for="(item,index) in reciveUserInfo" :key="index"> <view class="mesg"> <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>
三、結果
4、說明
對於一些詳情頁,好比有時咱們須要點贊數量+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
附加:改變的代碼:
2、子組件向父組件傳值
與微信小程序自定義組件中子組件向父組件傳值同樣的邏輯,都是經過事件,下面直接上代碼:
父組件index.vue
<template> <view class="content"> <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 class="" @click="sendMegToIndex"> 點我向父組件傳值 </view> </template> <script> export default{ methods:{ sendMegToIndex: function(){ // 向父組件傳值 this.$emit("send","我來自子組件") } } } </script>
最終結果: