不久前分享了我自己写的多选框组件(http://download.csdn.net/detail/lemon_zhao/9705162),基于vue1.0写的,最近写的项目是vue2.0的,顺道把这个组件做了下升级,1.0和2.0差别还是蛮大的,走了不少弯路,特地总结一下!!
1.套用官网上的一句话总结父子通信的问题,props down, events up,父级往子集通信用props属性,子集往父级通信用事件
2.父级页面代码如下,v-bind:status是传递给子级的参数,v-on:switched是触发的回调
<iphoneSwitcher v-bind:status="ipInfo.status" v-bind:canSwitch="true" v-bind:index="index" v-on:switched="ipSwitchCallback"></iphoneSwitcher>
3.子集代码如下,首次渲染的时候,在props里获取传递的数据,赋值给data函数,后面如果父级元素改变的话,用watch监听。传递给父级用methods里的doEmit触发父级的回调(1.0的dispatch被取消了...)
实现逻辑如下:
module.exports = {
name: 'iphoneSwitcher',
props: ['status','canSwitch','index','callBackName'],
data: function() {
var status = this.status;
var canSwitch = this.canSwitch;
var index = this.index || 0;
var callBackName = this.callBackName || null;
// console.log(callBackName)
var data = {
currentStatus: status,
currentCanSwitch: canSwitch,
currentIndex: index,
currenCallBackName: callBackName
}
return data
},
mounted: function(){
},
watch: {
status: function (val, oldVal) {
console.log('watch到currentStatus:' + val)
this.currentStatus = val;
},
canSwitch: function(val, oldVal){
console.log('watch到currentCanSwitch:' + val)
this.currentCanSwitch = val;
}
},
methods:{
doSwitcher: function(){
// console.log(this.currentStatus)
// console.log(this.currentCanSwitch)
var mySelf = this;
var currentCanSwitch = mySelf.currentCanSwitch;
var currentStatus = mySelf.currentStatus;
var currenCallBackName = mySelf.currenCallBackName;
// 判断能否点击
if (currentCanSwitch == true){
console.log('可以通过点击 修改!')
mySelf.currentStatus = !currentStatus;
mySelf.doEmit();
}
else{
console.log('不能通过点击 修改!触发父级回调!' + currenCallBackName)
var callBack = mySelf.$parent[currenCallBackName]
if (callBack){
callBack(mySelf.currentIndex)
}
}
},
doEmit: function(){
console.log('派发!')
this.$emit('switched', this.currentStatus,this.currentIndex);
}
}
}