vue使用.sync双向绑定

vue使用.sync双向绑定

流下了没有技术的泪水,这个问题搞了我一个多小时,自己太菜了,努力学习啊~~~~所以在我解决过后我觉得有必要写一篇简短的博客来描述这一段心酸往事,come to the point:
首先我们要明确自己有什么需求,就是子组件和父组件的通信,子组件修改值过后通知父组件,父组件修改过后传递给子组件,okay,建立两个组件一个是父组件(parent.vue),一个子组件(child.vue),既然要引用子组件,那么我们应该先写一个子组件
但是在这之前有必要先看一下效果:
在这里插入图片描述
我们在父组件中输入,就会将111传递到自组件,在子组件中输入就会传递到父组件,这样就实现了双向绑定啦
child.vue代码如下:

<template>
  <div>
    <el-input v-model="childInput"></el-input>
    父组件传递的值: {{fatherInput}}
  </div>
</template>
<script>
  export default {
    props: {
      fatherInput: {
        type: String,
        default: function () {
          return null
        }
      }
    },
    data() {
      return {
        childInput: ''
      }
    },
    watch: {
      fatherInput: function () { // 监听父组件传递过来的值
        if (this.fatherInput !== null) { // 如果父组件传递了值,我们就把值赋给子组件的输入框
          this.childInput = this.fatherInput
        }
      },
      childInput: function () { // 监听子组件的输入框的值,随时传递给父组件
        this.$emit('update:fatherInput', this.childInput); // 将子组件的输入框的值传递给父组件 父组件需要用.sync
      }
    }
  }
</script>

parent.vue代码如下:

<template>
  <div>
    父组件输入框:<el-input v-model="inputValue"></el-input>
    父组件值:{{inputValue}}
    <hr/>
    引用子组件:
    <child :fatherInput.sync="inputValue"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data() {
      return {
        inputValue: ''
      }
    }
  }
</script>

我觉得这个要充分运用到监听器,监听值的变化,并做出相应的操作

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值