vue子組件修改父組件中的值

  • 使用v-model傳值,在子組件中 ,使用value接收 ,在子組件中 觸發input方法 就可修改父組件傳遞過來的參數
<!-- 父組件 -->
<template>
    <div>
        <Child v-model="show"></Child>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                show: false
            }
        }
    }
</script>

<!-- 子組件 -->
<script>
  export default {
    props: {
      value: {
        type: Boolean,
        default: false
      }
    },
    methods:{
      changeValue(){
        this.$emit('input', true) // 父組件中的show會被更改成true
      }
    }
  }
</script>
  • 使用.sync 修飾符 給組件傳值的時候 使用.sync修飾符 子組件就可以同步修改父組件內容(.sync在2.0以後被移除,之後 從 2.3.0 起又重新引入了 .sync 修飾符,但是這次它只是作爲一個編譯時的語法糖存在。它會被擴展爲一個自動更新父組件屬性的 v-on 監聽器。)
<!-- 父組件 -->
<template>
  <div>
    <Child show.sync="show"></Child>
    <!-- 會被擴展成 -->
    <!-- <Child :show="bar" @update:show="val => bar = val"></Child> -->
  </div>
</template>
<script>
  export default {
    data() {
      return {
        show: false
      }
    }
  }
</script>

<!-- 子組件 -->
<script>
  export default {
    props: {
      show: {
        type: Boolean,
        default: false
      }
    },
    methods:{
      changeValue(){
        this.$emit('update:show', true) // 父組件中的show會被同步更改成true
      }
    }
  }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章