父子组件相互修改一个值的方法

152 阅读1分钟

方法一

父组件

<template>
  <div>
    父组件
    <input type="text"
           v-model="parentValue">
    <inputText :childValue="parentValue"
               @parentValue="(val)=>(parentValue=val)"></inputText>
    <!-- <inputText :value.sync="value"></inputText> -->
  </div>
</template>
<script>
import inputText from '../components/inputText.vue'
export default {
  components: { inputText },
  props: [],
  data () {
    return {
      parentValue: '0',
    }
  },
  watch: {
  },
  methods: {
  }
}
</script>
<style lang="scss" scoped>
</style>

子组件

<template>
  <div>
    子组件
    <input type="text"
           v-model="localValue">
  </div>
</template>
<script>
export default {
  name: 'children',
  components: {
  },
  props: {
    childValue: {
      type: String,
      required: true,
    }
  },
  data () {
    return {
    }
  },
  methods: {
  },
  computed: {
    localValue: {
      get () {
        return this.childValue;
      },
      set (val) {
        this.$emit('parentValue', val)
      }
    }
  },
  mounted () {
  },
}
</script>
<style  lang="scss" scoped></style>

方法二 sync属性

父组件

<template>
  <div>
    父组件
    <input type="text"
           v-model="parentValue">
    <!-- :childValue.sync="parentValue" -->
    <inputText :childValue.sync="parentValue"></inputText>
    <!-- 上面语句等于下面的语法糖 -->
    <!-- <inputText :childValue="parentValue"
               @update:childValue="val=>parentValue=val"></inputText> -->
  </div>
</template>
<script>
import inputText from '../components/inputText.vue'
export default {
  components: { inputText },
  props: [],
  data () {
    return {
      parentValue: '0',
    }
  },
  watch: {
  },
  methods: {
  }
}
</script>
<style lang="scss" scoped>
</style>

子组件

<template>
  <div>
    子组件
    <input type="text"
           v-model="localValue">
  </div>
</template>
<script>
export default {
  name: 'children',
  components: {
  },
  props: {
    childValue: {
      type: String,
      required: true,
    }
  },
  data () {
    return {
    }
  },
  methods: {
  },
  computed: {
    localValue: {
      get () {
        return this.childValue;
      },
      set (val) {
        // update:childValue 一定要加update
        this.$emit('update:childValue', val)
      }
    }
  },
  mounted () {
  },
}
</script>
<style  lang="scss" scoped></style>