1. 程式人生 > 其它 >轉載-vue2.0父子元件傳值-雙向繫結

轉載-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針對元件各種各樣狀態的傳遞。