vue 子组件改变父组件的值 实现双向绑定

发布时间 2023-11-09 09:43:44作者: qqcc1388

自定义子组件中接受外部传过来的值,然后在子组件中显示,当子组件操作完成后,需要把修改后的值返回给父组件,这就需要实现父子组件间的数据双向绑定,实现双向绑定可以通过以下2种方式实现:
1.通过this.$emit("change",val)的方式将数据传递回去,然后在父组件中监听该方法并获取返回val值,这种是最普遍的,也是最常用的

父组件:
<template>
  <div>
    <div>父组件:{{numberssss}}</div>
    <ce-shi :number="numberssss" @change="onNumberChange" />
  </div>
</template>
 
<script>
import ceShi from './ceshi'
export default {
  name: "login",
  components:{
    ceShi
  },
  data(){
    return{
      numberssss:123
    }
  },
  methods:{
     onNumberChange(val){
        this.numberssss = val
    }
  }
}
</script>
子组件:
<template>
  <div>
    <div>子组件:{{number}}</div>
    <button @click="changes">点击修改nunber</button>
  </div>
</template>
 
<script>
export default {
  name: "ceshi",
  props:{
    number:{}
  },
  methods:{
    changes(){
      this.$emit('update:number','666')
      this.$emit("change",'666')
    }
  }
}
</script>
<style scoped> </style>

2.通过this.$emit('update:number','666')来实现直接改变外部的数据,而不需要父组件主动监听和改变数据。需要注意的是,该功能需要配置.sync语法糖才可以生效,使用时需要注意着点

父组件:
<template>
  <div>
    <div>父组件:{{numberssss}}</div>
    <ce-shi :number.sync="numberssss"/>
  </div>
</template>
 
<script>
import ceShi from './ceshi'
export default {
  name: "login",
  components:{
    ceShi
  },
  data(){
    return{
      numberssss:123
    }
  },
  methods:{
     onNumberChange(val){
        this.numberssss = val
    }
  }
}
</script>
子组件:
<template>
  <div>
    <div>子组件:{{number}}</div>
    <button @click="changes">点击修改nunber</button>
  </div>
</template>
 
<script>
export default {
  name: "ceshi",
  props:{
    number:{}
  },
  methods:{
    changes(){
      this.$emit('update:number','666')
    }
  }
}
</script>
<style scoped> </style>