Vue父子组件实现数据‘双向绑定’的传参方法。(适用多个v-model)

<div class="topLine">
        <singler :date.sync="date" :name='"统计周期"'></singler>
        <singler :name='"变压器"' :devices='devices' v-model='device'></singler>
</div>

父组件代码如上。

子组件代码如下。

// 使用组件时,如果是选择器,则使用v-model绑定值,如果是输入框或者日期选择器,是v-bind:xxx.sync 
<template>
    <div class="singler">
        <span v-if='name'>{{name}}:</span>
        <el-select @change="$emit('changeDevice',$event)" v-if='devices' :popper-append-to-body=true :value="device" popper-class='singler_select'>
            <el-option v-for="item in devices" :key="item.id" :label="item" :value="item">
            </el-option>
        </el-select>
        <el-date-picker v-if='date' format="yyyy/MM/dd" v-model="currentDate" type="daterange" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <input v-if='inputValue' v-model="inputVal" :disabled='disabled' type="text" :placeholder='placeholder'>
    </div>
</template>


<script>
export default {
    props: ['name','devices','date','device','placeholder','inputValue','disabled'],
    model:{
        prop:'device',
        event:'changeDevice'
    },
    computed:{
        currentDate:{
            get(){
                return this.date
            },
            set(val){
                this.$emit('update:date',val)  //父组件使用sync语法时,事件名必须为update:xxx
            }
        },
        inputVal:{
            get(){
                return this.inputValue
            },
            set(val){
                this.$emit('update:inputValue',val)
            }
        }
    },
}
</script>

当父组件使用v-model来传值时,子组件可以使用设置model来实现prop数据’双向绑定‘。

当你想要实现双向绑定的数据过多时。则可采用vue自带的sync语法糖。该语法糖封装了类似v-model的功能。

https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6

点击上面链接可以看官方文档。

猜你喜欢

转载自blog.csdn.net/q275757160/article/details/88973393