Vue2的组件props通信方式
关于这一点的修改官方给的解释:
prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解。
虽然废弃了props的双向绑定对于整个项目整体而言是有利且正确的,但是在某些时候我们确实需要从组件内部修改props的需求
联动组件代码:
<template>
<!-- self 只是作用在当前的元素上,子元素不出发该函数 -->
<div class="pick-bg" v-show="childselectArea" @click.self="cancelClick">
<div class="pick-com">
<div class="dp-header">
<div class="dp-item dp-left vux-datetime-cancel" data-role="cancel" @click="cancelClick">取消</div>
<!-- stop 阻止事件的冒泡 -->
<div class="dp-item dp-right vux-datetime-confirm" data-role="confirm" @click.stop="sureClick">确定</div>
</div>
<picker :data='addressList' :fixed-columns="columns" :columns="3" v-model='selectAddList' @on-change='change' ref="picker"></picker>
</div>
</div>
</template>
<script>
import { Picker } from 'vux'
import { mapState } from 'vuex'
import gzw from '@/modules/gzw'
export default {
components: {
Picker
},
data() {
return {
selectAddList: [],
resultObj: {},
childselectArea: this.selectArea // ①创建props属性result的副本--myResult
}
},
props: ['selectArea','columns'],
created() {
this.$store.dispatch('gzw/getAddressList')
},
computed: {
...mapState({
addressList: state => state.gzw.addresList,
})
},
watch: {
selectArea(val) { // ②监听外部对props属性result的变更,并同步到组件内的data属性myResult中
this.childselectArea = val
},
childselectArea(val) {
this.$emit("on-result-change", {state: val, result: this.resultObj});//③组件内对myResult变更后向外部发送事件通知
}
},
methods: {
change(value) {
// console.log('获取的value的值', value)
// console.log(this.$refs.picker.getNameValues() + '获取的name')
},
cancelClick(event) {
this.childselectArea = !this.childselectArea
},
sureClick() {
this.resultObj = {'name': this.$refs.picker.getNameValues(), 'code': this.selectAddList}
this.childselectArea = !this.childselectArea
}
}
}
</script>
<style>
.pick-bg {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.pick-com {
position: absolute;
bottom: 0;
width: 100%;
}
.dp-header {
height: 40px;
line-height: 40px;
background-color: #fff;
}
.dp-item {
width: 60px;
text-align: center;
color: #828282;
}
.dp-item:active {
color: #298;
background-color: '';
}
.dp-left {
float: left;
}
.dp-right {
float: right;
}
</style>
外部调用:
<div class="map">
地图导航
<cell title="地区" :value="value" @click.native="selectAddressClick" is-link></cell>
<coustomer-pick :selectArea="selectAreaAAAA" @on-result-change="onResultChange"></coustomer-pick>
</div>
methods: {
selectAddressClick() { // 选择地区事件
this.selectAreaAAAA = !this.selectAreaAAAA
},
onResultChange(val) {
console.log('子组件改变之后通知父组件' + JSON.stringify(val))
this.selectAreaAAAA = val.state
this.value = val.result.name;
console.log(val.result.code)
}
}