当前位置: 代码迷 >> 综合 >> vue 双向绑定 子组件input 动态修改父组件值
  详细解决方案

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

热度:4   发布时间:2024-02-28 18:35:12.0

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

一:常规方法

<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 propcomputed: {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 propcomputed: {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 propcomputed: {config: {get() {return this.value},set(val) {this.$emit('input', val)}}}});export default {name: 'demo01',data(){return{title:true,}}}
</script>

 

  相关解决方案