溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue父子組件之模態(tài)框狀態(tài)綁定的示例分析

發(fā)布時(shí)間:2021-08-30 13:56:36 來源:億速云 閱讀:146 作者:小新 欄目:web開發(fā)

小編給大家分享一下vue父子組件之模態(tài)框狀態(tài)綁定的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

日常開發(fā)中經(jīng)常遇到的一個(gè)場景,父組件有很多操作,需要彈窗,例如:

<template>
  <div class="page-xxx">
    //點(diǎn)擊打開新增彈窗
    <button>新增</button>
    //點(diǎn)擊打開編輯彈窗
    <button>編輯</button>
    //點(diǎn)擊打開詳情彈窗
    <button>詳情</button>
    <Add :showAdd="false"></Add>
    <Edit :showEdit="false"></Edit>
    <Detail :showDetail="false"></Detail>
  </div>
</template>

子組件:

<div class="page-add">
  <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
  data() {
    return {
      dialogVisible: false,
    }
  },
  methods: {
    handleClose(val) {
      this.dialogVisible= false
    },
  },
}
</script>

如何實(shí)現(xiàn)子組件和父組件模態(tài)框狀態(tài)的同步

方案一:使用.sync 修飾符

父組件:

<template>
  <div class="page-xxx">
    //點(diǎn)擊打開新增彈窗
    <button @click="show = true">新增</button>
    <Add :show.sync="show"></Add>
  </div>
</template>

子組件:

<div class="page-add">
  <el-dialog:visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
  props: {
    show: {
      type: Boolean
    }
  },
  watch: {
    show(value) {
      this.dialogVisible= value
    }
  },
  data() {
    return {
      dialogVisible: false,
    }
  },
  methods: {
    handleClose(val) {
      this.$emit('update:show', false);
    },
  },
}
</script>

方案二:使用v-model

父組件:

<template>
  <div class="page-xxx">
    //點(diǎn)擊打開新增彈窗
    <button @click="show = true">新增</button>
    <Add v-model="show"></Add>
  </div>
</template>

子組件:

<div class="page-add">
  <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog>
</div>
<script>
export default {
  props: {
    show: {
      type: Boolean
    }
  },
  watch: {
    show(value) {
      this.dialogVisible= value
    }
  },
  data() {
    return {
      dialogVisible: false,
    }
  },
  methods: {
    handleClose(val) {
      this.$emit('input', false)
    },
  },
}
</script>

computed OR watch ?

對于上面的兩種方案,子組件內(nèi)部還可以使用計(jì)算屬性的寫法

computed
export default {
  props: {
    show: {
      type: Boolean
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        return this.$emit('input', value)
      },
    },
  },
  methods: {
    handleClose(val) {},
  },
}

以上是“vue父子組件之模態(tài)框狀態(tài)綁定的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI