vue 双向绑定 子组件input 动态修改父组件值

让子组件修改父组件中的变量:

一:常规方法

<template>
  <div>
    <h1>实现双向绑定方法-基础</h1>
    //父组件
    <h1>{{fatherTitle}}</h1>
    <myComponent :title="fatherTitle" @titleFunc="fatherTitleFunction"></myComponent>
  </div>
</template>
<script>
  import Vue from 'vue'
  //子组件
  Vue.component('myComponent', {
    template: `<div>
                //子组件
                <h2>{{title}}</h2>
               <input type="text" v-model="config">
             </div>`,
    props: ['title'], //接收一个 value prop
    computed: {
      config: {
        get() {
          return this.title
        },
        set(val) {
          this.$emit('titleFunc', val)
        }
      }
    }
  });
  export default {
    name: 'demo01',
    data() {
      return {
        fatherTitle: 'sync修饰符',
      }
    },
    methods: {
      fatherTitleFunction(val){
        this.fatherTitle=val
      }
    }
  }
</script>

二:.sync 

我们先看下官方文档:vue .sync 修饰符,从 2.3.0 起我们重新引入了 .sync 修饰符,它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。相当于上面的常规方法的一种简化

<template>
  <div>
    <h1>实现双向绑定方法 .sync</h1>
    //父组件
    <h1>{{fatherTitle}}</h1>
    <myComponent :title.sync="fatherTitle"></myComponent>
  </div>
</template>
<script>
  import Vue from 'vue'
  //子组件
  Vue.component('myComponent', {
    template: `<div>
                //子组件
                <h2>{{title}}</h2>
               <input type="text" v-model="config">
             </div>`,
    props: ['title'], //接收一个 value prop
    computed: {
      config: {
        get() {
          return this.title
        },
        set(val) {
          this.$emit('update:title', val)
        }
      }
    }
  });
  export default {
    name: 'demo01',
    data() {
      return {
        fatherTitle: 'sync修饰符',
      }
    }
  }
</script>

三:v-model

v-model是 Vue2 中唯一支持双向绑定的指令,用于表单控件绑定,但不代表它只能用在表单控件之上.而且v-modal和.sync 一样都是语法糖 参考官方文档:在组件上使用 v-model

<template>
  <div>
    <h1>实现双向绑定方法 v-model</h1>
    //父组件中引用
    <h1>{{title}}</h1>用来测试这里显示'111111',(测试1)
    <myComponent v-model="title"></myComponent>
    这里title是动态值,在data里可以自己设置默认值,假如这里我们设置为“111111”
  </div>
</template>

<script>
  import Vue from 'vue'
  //子组件
  Vue.component('myComponent', {
    template: `<div>
                <h2>{{value}}</h2>
               <input type="text" v-model="config">
             </div>`,
    props: ['value'], //接收一个 value prop
    computed: {
      config: {
        get() {
          return this.value
        },
        set(val) {
          this.$emit('input', val)
        }
      }
    }
  });
  export default {
    name: 'demo01',
    data(){
      return{
        title:true,
      }
    }
  }
</script>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值