vue - $emit input and v-model (the content of the parent component text box and the child component text box are updated synchronously)

The content of the parent component text box and the child component text box of the business scenario are updated synchronously

Code directly

Parent component

<template>
  <div style="padding:30px">
    <div>我是父组件</div>
    <a-input v-model="parent" style="width:30%" placeholder="我是父组件"></a-input>
    <children v-model="parent" :parent="parent"></children>
  </div>
</template>

<script>
import {
    
    Input} from "ant-design-vue"
import children from "./children"
export default {
    
    
  components: {
    
    
    aInput: Input,
    children
  },
  data() {
    
    
    return {
    
    
      parent: ""
    }
  }
}
</script>

Subassembly

<template>
  <div style="margin-top: 30px">
    <div>我是子组件</div>
    <a-input
      v-model="parentVal"
      style="width: 30%"
      placeholder="我是子组件"
    ></a-input>
  </div>
</template>

<script>
import {
    
     Input } from "ant-design-vue";
export default {
    
    
  components: {
    
    
    aInput: Input,
  },
  props: {
    
    
    parent: {
    
    
      type: String,
      default: ''
    }
  },
  data() {
    
    
    return {
    
    
        parentVal: ""
    };
  },
  watch: {
    
    
    parent(newVal, oldVal){
    
    
        this.parentVal = newVal
    },
    parentVal(newVal, oldVal){
    
    
      this.$emit("input", newVal)
    }
  },
};
</script>

Modify the text box content of the parent component and update the child component synchronously

Insert picture description here

Modify the text box content of the child component and the parent component will be updated synchronously

Insert picture description here

Guess you like

Origin blog.csdn.net/hu1628299958/article/details/110326513