v-mode只能進行單個雙向繫結值而使用.sync可支援多個雙向繫結值,當然,具體使用哪個可以參照自己的使用場景來區分
透過.sync 實現父子資料雙向繫結的例子
子元件
<template>
<view>
<button class="pz-btn" plain="true" @click="dopic">拍照(≤5張,每張<3M)</button>
<view class="uni-flex uni-column" v-for="(item, index) in piclist">
<view class="uni-flex uni-column">
<image :src="item.pic" style="width: 100%;height:150upx">
<text>{{ item.txt }}</text>
</view>
</view>
</view>
</template>
<script>
export default {
name:"makpic",
props:{
piclist:{
require: true,
type:Array,
default () {
return []
}
}
},
data() {
return {
};
},
methods:{
dopic:function(){
let piclist = this.piclist;
let self = this;
uni.chooseImage({
count: 1,
sizeType: ['original'],
sourceType: ['camera'],
success: function (res) {
console.log(res.tempFilePaths[0]);
var pic = res.tempFilePaths[0];
var txt = "未檢測到經緯度";
uni.getLocation({
type: 'wgs84',
success: function (res) {
txt = "經度:"+ res.longitude + " 維度:"+res.latitude;
piclist.push({
pic:pic,
txt:txt
});
self.$emit("update:piclist",piclist);
},
fail:function(){
piclist.push({
pic:pic,
txt:txt
});
self.$emit("update:piclist",piclist);
}
});
}
});
},
}
}
</script>
父元件
<template>
<view class="body-con">
<uni-forms label-width="100" :value="formData">
<uni-group >
<uni-forms-item required label="aaaa">
<uni-easyinput type="text" v-model="formData.sjdw" />
<makpic :piclist.sync="formData.sjdw_pic"></makpic>
</uni-forms-item>
<uni-forms-item required label="bbbb">
<uni-easyinput type="text" />
<makpic :piclist.sync="formData.sjjz_pic"></makpic>
</uni-forms-item>
</uni-group >
<button @click="subform">提交</button>
</uni-forms>
</view>
</template>
<script>
export default {
data() {
return {
formData:{
"sjdw_pic":[],
"sjjz_pic":[],
"sjjz_adress_pic":[],
}
};
},
methods:{
subform(){
console.log(this.formData);
}
}
}
</script>
.sync 即可雙向繫結,但是還是要依靠子元件 $emit 去觸發 update:prop名 實現修改父元件的變數值實現雙向資料流,如果直接對prop的屬性直接賦值,依然會出現報錯。
事實上, .sync 修飾符是一個簡寫,它做了一件事情
<template>
<makpic :piclist.sync="formData.sjdw_pic"></makpic>
<!-- 等價於 -->
<makpic :piclist="formData.sjdw_pic" @updata:piclist="formData.sjdw_pic = $event"></makpic>
<!-- 這裡的$event就是子元件$emit傳遞的引數 -->
</template>
本作品採用《CC 協議》,轉載必須註明作者和本文連結