优雅的实现vue父子组件的value双向绑定

需求:父子组件value的双向绑定

  1. v-model可以拆分为@input和:value
  2. v-model实现双向绑定是@input的回调函数中,执行赋值给value的语法糖
  3. 子组件向父组件通讯,第一个参数为input,其实是给父组件中子组件@input回调中传入参数并且设置对应value
  4. 改变父组件中对应双向绑定的值,即可实现双向绑定
  5. 只能实现子组件最上级元素的value绑定,适用于父组件控制子组件显示隐藏等

父组件:

<template>
	<div id='testModel'>
		<button class="parent" @click="change">父组件按钮</button>
		<testChild v-model="isShow" :text="text"</testChild>
		
		<!-- 以下是demo解释 -->
		<input type="text" v-model="inputVlu">
		<!-- v-model可以做以下拆分 -->
		<input type="text" @input="ipt" :value="inputVlu">
		<!-- @input是v-on:input的语法糖 -->
		<input type="text" v-on:input="ipt" :value="inputVlu">
		
	</div>
</template>

<script>
  import testChild from './testChild';
    export default {
        name: "testModel",
      components:{testChild},
        data() {
            return {
              isShow:true,
              text:'哈哈哈',
              inputVlu:'inputVlu',
            }
        },
      methods:{
        change(){
          this.isShow=!this.isShow;
        }
      }
    }
</script>

<style lang="scss" type="text/scss" scoped>
    #testModel {

    }
</style>

子组件:

<template>
  <div id='testChild' :value="value" @input="setInput">
    <div class="box" v-show="value">{{text}}</div>
    <button @click="hid">子组件隐藏按钮</button>
  </div>
</template>

<script>
  export default {
    name: "testChild",
    data() {
      return {}
    },
    props: {
      value: {
        type: Boolean,
        redirect: true,
      },
      text:{
        type: String,
        default:'信息',
      },
    },
    methods: {
      setInput(value) {
        this.$emit('input', value);
        //向父组件传递数据,以input为对应函数key
        //父组件中v-on:ipnut中ipnut的回调接收这里的value值
      },
      hid(){
        this.$emit('input', !this.value);
      },
    },

  }
</script>

<style lang="scss" type="text/scss" scoped>
  #testChild {
    .box {
      width: 100px;
      height: 100px;
      background-color: pink;
    }
  }
</style>


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值