Vue.js移动端左滑删除组件的实现代码
发布时间:2023-05-18 16:24:37
Vue.js移动端左滑删除组件的实现代码
步:创建一个DeleteButton组件
<template>
<div class="delete-button" v-show="show" v-touch:swipeleft="swipeleft">
<span class="delete-text">{{ text }}</span>
</div>
</template>
<script>
export default {
props: {
text: String,
deleteFunc: Function
},
data() {
return {
show: false
}
},
methods: {
swipeleft() {
this.show = false
this.deleteFunc()
}
}
}
</script>
<style scoped>
.delete-button {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
line-height: 50px;
text-align: center;
background-color: #f44336;
color: #ffffff;
font-size: 16px;
font-weight: bold;
z-index: 9999;
transition: transform 0.3s, opacity 0.3s;
transform: translate(0, 100%);
opacity: 0;
}
.delete-button.show {
transform: translate(0, 0);
opacity: 1;
}
</style>
第二步:在需要使用删除功能的列表项中引入DeleteButton组件
<template>
<div class="list-item" v-touch:swipeleft="showButton" v-touch:swiperight="hideButton">
<div class="list-content">{{ text }}</div>
<delete-button :text="'删除'" :deleteFunc="deleteItem" :show="show"></delete-button>
</div>
</template>
<script>
import DeleteButton from './DeleteButton.vue'
export default {
components: {
DeleteButton
},
props: {
text: String
},
data() {
return {
show: false
}
},
methods: {
showButton() {
this.show = true
},
hideButton() {
this.show = false
},
deleteItem() {
this.$emit('delete-item')
}
}
}
</script>
<style scoped>
.list-item {
position: relative;
height: 50px;
line-height: 50px;
background-color: #ffffff;
padding: 10px;
border-bottom: 1px solid #f1f1f1;
}
.list-content {
float: left;
width: calc(100% - 70px);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.delete-button {
position: absolute;
bottom: 0;
right: 0;
}
</style>
第三步:在需要使用删除功能的列表中引入列表项组件
<template>
<div class="list">
<list-item v-for="(item, index) in list" :key="index" :text="item.text" @delete-item="deleteItem(index)"></list-item>
</div>
</template>
<script>
import ListItem from './ListItem.vue'
export default {
components: {
ListItem
},
data() {
return {
list: [
{
text: 'Item 1'
},
{
text: 'Item 2'
},
{
text: 'Item 3'
}
]
}
},
methods: {
deleteItem(index) {
this.list.splice(index, 1)
}
}
}
</script>
<style scoped>
.list {
margin: 10px;
}
</style>
使用vue-touch来实现左滑删减的效果,配合使用了两个自定义指令,分别是v-touch:swipeleft和v-touch:swiperight,分别对应左滑和右滑触发的函数。DeleteButton组件是左滑出现的删除按钮,ListItem组件是右滑出现删除按钮的列表项。整体的样式可以根据项目需求进行调整。
