需求:点击【更多操作】,显示【编辑】【删除】,点击灰色区域关闭弹层
DOM结构:
<div class="more-operations"> <transition name="popup"> <div class="popup" v-show="isShow" @click="handleClose"> <div class="btns"> <div @click="handleEdit">编辑</div> <div @click.stop="handleDelete">删除</div> </div> </div> </transition> </div>
methods:
methods: { handleEdit() { this.$emit('edit') }, handleDelete() { this.$emit('delete') }, handleClose() { this.isShow = false } }
css:
.more-operations { .popup-enter-active, .popup-leave-active { transition: opacity 0.2s linear; } .popup-enter, .popup-leave-to { // transform: translate3d(100%, 0, 0); opacity: 0; } .popup-enter-to, .popup-leave { // transform: translate3d(0, 0, 0); opacity: 1; } .popup { position: fixed; width: 100%; height: 100%; top: 0; bottom: 0; left: 0; right: 0; background-color: rgba(#000, 0.6); .btns { position: absolute; bottom: 70px; left: 0; right: 0; display: flex; flex-direction: column; align-items: center; > div { width: calc(100% - 60px); line-height: 50px; text-align: center; border-radius: 25px; background-color: #fff; font-size: 18px; color: #1288fe; } > div:last-of-type { color: #fc5e5e; margin-top: 15px; } } } .popup::before { content: ''; } }
前提知识点:
1、v-model是 value 属性和 input 事件的语法糖,v-model='name' 相当于写了 :value='name' @input="(e)=>name=e.target.value"
2、v-model的默认属性和事件可以修改,组件内在model中设置prop和event(不改也可以用默认的value值和input事件)
3、sync修饰符也是一个语法糖, :age.sync='age' 相当于写了 :age='age' @update:age='age=$event' ,所以在组件内修改age时,用的事件名就是 update:age
一、使用v-mode绑定数据
组件内:
props: { value: { type: Boolean, require: true } }, // model: { prop: 'value', event: 'input' }, // 自定义model时,是可以依然使用value属性和input事件的,此时model可以不写 computed: { isShow: { get() { return this.value }, set(flag) { this.$emit('input', flag) } } }
使用:
<MoreOperations v-model='isShow' @edit='handleEdit' @delete='handleDelete' />
二、使用sync绑定数据
组件内:
props: { visible: { type: Boolean, require: true } }, computed: { isShow: { get() { return this.visible }, set(flag) { this.$emit('update:visible', flag) } } }
使用:
<MoreOperations :visible.sync='isShow' @edit='handleEdit' @delete='handleDelete' />
三、通用
如果在组件内设置 model 为 model: { prop: 'visible', event: 'update:visible' }
model: { prop: 'visible', event: 'update:visible' }, props: { visible: { type: Boolean, require: true } }, computed: { isShow: { get() { return this.visible }, set(flag) { this.$emit('update:visible', flag) } } }
使用时
<MoreOperations v-model='isShow' @edit='handleEdit' @delete='handleDelete' />
或
<MoreOperations :visible.sync='isShow' @edit='handleEdit' @delete='handleDelete' />
效果是一样的,如果使用sync的方式,那么组件内model可以注释掉