文章目錄
- 一、介紹
- 二、語法
- 三、代碼示例
一、介紹
作用:可以實現 子組件 與 父組件數據 的 雙向綁定,簡化代碼
簡單理解:子組件可以修改父組件傳過來的props值
特點:prop屬性名,可以自定義,非固定為value
但是.sync沒有v-model方便,所以當屬性名確定為value,即表單元素的時候,就使用v-model
**場景 ** 封裝彈框類的基礎組件, visible屬性 true顯示 false隱藏
本質 .sync修飾符 就是 :屬性名 和 @update:屬性名 合寫
二、語法
父組件
// .sync寫法
<BaseDialog :visible.sync="isShow" />
--------------------------------------
// 完整寫法
<BaseDialog :visible="isShow" @update:visible="isShow = $event"
/>
子組件
props: {visible: Boolean
},this.$emit('update:visible', false)
三、代碼示例
App.vue
<template><div class="app"><button @click="openDialog">退出按鈕</button><!-- isShow.sync => :isShow="isShow" @update:isShow="isShow=$event" --><BaseDialog :isShow.sync="isShow"></BaseDialog></div>
</template><script>
import BaseDialog from './components/BaseDialog.vue'
export default {data() {return {isShow: false,}},methods: {openDialog() {this.isShow = true// console.log(document.querySelectorAll('.box')); },},components: {BaseDialog,},
}
</script><style>
</style>
BaseDialog.vue
<template><div class="base-dialog-wrap" v-show="isShow"><div class="base-dialog"><div class="title"><h3>溫馨提示:</h3><button class="close" @click="closeDialog">x</button></div><div class="content"><p>你確認要退出本系統么?</p></div><div class="footer"><button>確認</button><button>取消</button></div></div></div>
</template><script>
export default {props: {isShow: Boolean,},methods:{closeDialog(){this.$emit('update:isShow',false)}}
}
</script><style scoped>
.base-dialog-wrap {width: 300px;height: 200px;box-shadow: 2px 2px 2px 2px #ccc;position: fixed;left: 50%;top: 50%;transform: translate(-50%, -50%);padding: 0 10px;
}
.base-dialog .title {display: flex;justify-content: space-between;align-items: center;border-bottom: 2px solid #000;
}
.base-dialog .content {margin-top: 38px;
}
.base-dialog .title .close {width: 20px;height: 20px;cursor: pointer;line-height: 10px;
}
.footer {display: flex;justify-content: flex-end;margin-top: 26px;
}
.footer button {width: 80px;height: 40px;
}
.footer button:nth-child(1) {margin-right: 10px;cursor: pointer;
}
</style>