el-select组件与父组件实现双向数据绑定

封装成组件的下拉框如何与父组件实现双向数据绑定?

之前的做法:

下拉框组件
<template>
  <el-select v-model="curFruit" @change="change">
    <el-option
      v-for="(item,index) in fruits"
      :key="index"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>
</template>
<script>
  export default {
    name: 'my-fruits',
    data() {
      return{
        fruits: [
          {label: '苹果', value: 'apple'},
          {label: '香蕉', value: 'banana'},
          {label: '西瓜', value: 'watermelon'}
        ]
      },
      props: {
        curFruit: {
          type: [String,Number],
          default: ''
        }
      }
    },
    methods: {
      change(val) {
        this.$emit('change',val)
      }
    }
  }
</script>
父组件
<template>
  <fruit :curFruit="fruit" @change="change"></fruit>
</template>
<script>
  import fruit from "./components/fruit"
  export default {
    name: 'index',
    components:{
      fruit
    },
    data() {
      return{
        fruit: ''
      }
    },
    methods: {
      change(val) {
        console.log('子组件传递的水果value-->',val);
        // 操作逻辑...
      }
    }
  }
</script>

在vue 2.2.0之后新增了model属性,方便组件之间传递值

现在的常用做法

通过接收curFruit(有时候让下拉框自动选择url中携带的参数),通过change事件抛出选中的值
子组件

<template>
  <el-select
    v-model="curFruit"
    @change="$emit('change',$event)"
  >
    <el-option
      v-for="(item,index) in fruits"
      :key="index"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>
</template>
<script>
  export default {
    name: 'my-fruits',
    model: {
      prop: 'curFruit',
      event: 'change'
    },
    data() {
      return{
        fruits: [
          {label: '苹果', value: 'apple'},
          {label: '香蕉', value: 'banana'},
          {label: '西瓜', value: 'watermelon'}
        ]
      }
    }
  }
</script>

父组件
通过v-model绑定curFruit,将值传递给子组件的prop(curFruit),同时接收子组件的event(change)事件抛出的值

<template>
  <fruit v-model="curFruit"></fruit>
</template>
<script>
  import fruit from "./components/fruit"
  export default {
    name: 'index',
    components:{
      fruit
    },
    data() {
      return{
        curFruit: '',
        params: {
          fruit: ''
        }
      }
    },
    watch: {
      curFruit: {
        handler(newVal,oldVal) {
          // 监听curFruit的值给参数对象,发请求
          this.params.fruit = newVal
        }
      }
    }
  }
</script>

按时下班是程序员毕生追求,加油!!

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值