Vue父子组件间传值

2019-05-05  本文已影响0人  异想天不开_9950

一、父组件向子组件传值(通过 props 属性)

<div @touchmove.prevent>
    <datePicker
        ref="startPicker"
        :value="startPickerValue"
        @confirm="startDateConfirm">
    </datePicker>
</div>
import datePicker from '@/components/datePicker';

data() {
    startPickerValue: 0,
},
components: {
    datePicker
},
<mt-picker ref="picker" :slots="slots" :visible-item-count=7 @change="onValuesChange"></mt-picker>

子组件方法中通过 this.value 来获取数值

/**
 * 组件的属性列表
 */
// 定义父组件传入子组件的值
props: {
    value: null
},
// 这是一个观察属性,父组件传给子组件值后就渲染时间选择器控件
watch: {
    value(val) {
        this.currentValue = val;
        this.setDefaultIndex(this.currentValue);
    }
},
// 设置默认值
setDefaultIndex(res) {

    var time = new Date(res)
    let str = this.setDay(time);
    this.slots[0].defaultIndex = this.dates.indexOf(str);

    var hour = time.getHours()
    this.slots[1].defaultIndex = this.hours.indexOf(parseInt(hour));

    var minute = time.getMinutes()
    if (minute < 10) { minute = '0' + minute }
        this.slots[2].defaultIndex = this.minutes.indexOf(minute);

        var date = this.formatTrans(str, hour+":"+minute); // "2019-04-29 12:04"
        this.currentValue = new Date(date.replace(/-/g, '/'));
    }
},

二、子组件向父组件传值(通过 emit 事件)

需要手动触发获取

<div @click="confirm">确定</div>
/**
 * 组件的方法列表
 */
confirm() {
    let res = this.$refs.picker.getValues();
    var date = this.dateFormatTrans(res);
    this.currentValue = new Date(date.replace(/-/g, '/'));

    //confirm 事件触发后,自动触发父组件 confirm 事件
    this.$emit('confirm', this.currentValue);
    this.isDisplay = false;
},

通过 @confirm="startDateConfirm" 把子组件的事件传递给父组件的自定义事件

<div @touchmove.prevent>
    <datePicker
        ref="startPicker"
        :value="startPickerValue"
        @confirm="startDateConfirm">
    </datePicker>
</div>
// 提交事件
startDateConfirm (value) {
    this.startPickerValue = value;
    // 时间选择器确定按钮,并把时间转换成我们需要的时间格式
    var startDate = this.formatStartDateMin(this.startPickerValue).split(' ');

    this.startDayValue = startDate[0];
    this.startMinValue = startDate[1];

    startDate = this.formatTrans(this.startDayValue, this.startMinValue);
    this.startPickerValue = new Date(startDate.replace(/-/g, '/'));
},
上一篇 下一篇

猜你喜欢

热点阅读