转载-vue2.0父子组件传值-双向绑定

作者不知道是谁了

方式一:

子组件

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
    // 好像没有model设置也能生效?
  model: {
    prop: 'msg',
    event: 'changeMsg'
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('changeMsg', 'mother')
      } else {
        this.$emit('changeMsg', 'father')
      }
    }
  }
}
</script>

父组件

<template>
  <div>
    <child :msg="msg" @changeMsg="changeMsg"></child>
    <div>父亲:{{msg}}</div>
    <button @click="fatherBtn">父亲</button>
  </div>
</template>

<script>
import Child from '@/components/Child'
export default {
  name: 'Index',
  components: {
    Child
  },
  data () {
    return {
      msg: ''
    }
  },
  methods: {
    changeMsg (e) {
      this.msg = e
    },
    fatherBtn () {
      if (this.msg === 'father') {
        this.msg = 'mother'
      } else {
        this.msg = 'father'
      }
    }
  }
}
</script>

父组件通过prop修改子组件的数据状态,子组件通过$emit发送事件(event)信号,通知父组件修改父组件内的数据状态,同时父组件需要监听相关的event。

方式二:

使用v-model进行双向绑定,v-model是一种语法糖

<child v-model="msg"></child>

等价于

<child :value="msg" @input="changeMsg"></child>

但是,如果我们需要指定子组件的prop,和监听的event应该怎么做呢?
只需要在子组件中指定model即可

model: {
  prop: 'msg',
  event: 'changeMsg'
}

完整子组件代码如下:

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
  model: {
    prop: 'msg',
    event: 'changeMsg'
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('changeMsg', 'mother')
      } else {
        this.$emit('changeMsg', 'father')
      }
    }
  }
}
</script>

方式三:

使用 .sync ,也是一种语法糖

<child :msg.sync="msg"></child>

等价于

<child :msg="msg" @update:msg="changeMsg"></child>

子组件只需要 emit('update:msg')即可。
完整子组件代码如下:

<template>
  <div>
    <div>儿子:{{msg}}</div>
    <button @click="childBtn">儿子</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: {
    msg: {
      require: true,
      type: String,
      default () {
        return ''
      }
    }
  },
  methods: {
    childBtn () {
      if (this.msg === 'father') {
        this.$emit('update:msg', 'mother')
      } else {
        this.$emit('update:msg', 'father')
      }
    }
  }
}
</script>

方式二v-model与方式三sync有什么区别呢?

1、v-model只能指定一个属性,而sync可以使用在任意多个属性上。
2、v-model更多的是使用在表示该组件特有的“value”的变化,sync针对组件各种各样状态的传递。

posted @ 2022-05-18 14:40  DurianTRY  阅读(397)  评论(0编辑  收藏  举报