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>
</template>