需求:实现双击表格行跳转详情编辑页面,编辑完返回时定位到之前选择的表格行
1.修改了uniapp官方组件库uni-table
中的uni-tr
的源码,添加@click事件,添加<slot name="scroll"></slot>
插槽
<block><slot name="scroll"></slot><viewclass="uni-table-tr"@click="rowClick":class="{ 'is-active': isActive }"><viewv-if="selection === 'selection'"class="checkbox":class="{ 'tr-table--border': border, 'checkbox-head': isHeadTr }"><table-checkbox:checked="checked":indeterminate="indeterminate":disabled="disabled"@checkboxSelected="checkboxSelected"></table-checkbox></view><slot></slot></view></block>
添加<slot name="scroll"></slot>
插槽的目的是搭配scroll-view
标签与其scroll-into-view
属性,用于渲染滚动定位元素,实现滚动定位
<template/>
和 <block/>
并不是一个组件,它们仅仅是一个包装元素,不会在页面中做任何渲染,只接受控制属性。
但实际使用中发现<template/>
做包装元素会提示编译错误,使用 <block/>
则很正常
模拟双击效果
rowClick(e) {let currentTime = e.timeStamp;if (currentTime - this.lastTapTime < 300) {// 执行双击操作this.$emit("rowClick", "");} // 更新点击时间this.lastTapTime = currentTime;},
2.页面中使用uni-table
,使用scroll-view滚动,使用其scroll-into-view属性实现滚动定位
<template><scroll-view scroll-y="true" class="scroll" :scroll-into-view="scrollid"><view class="table-content"><uni-tableref="table2"stripeemptyText="暂无更多数据"class="table-content"type="selection"@selection-change="selectionChange2"><uni-tr isHeadTr="true"><uni-th align="center" width="80">序号</uni-th><uni-th align="center" width="150">计划开始时间</uni-th><uni-th align="center" width="150">计划结束时间</uni-th></uni-tr><uni-trv-for="(item, index) in listDataSucess":key="item.id"@rowClick="rowClick(item)":is-active="item.id === scrollintoid"><template #scroll><text id="scrollId" v-if="item.id === scrollintoid"></text></template><uni-td align="center"><view>{{ index + 1 }}</view></uni-td><uni-td align="center">{{ item.kssj ? item.kssj : "" }}</uni-td><uni-td align="center">{{ item.jssj ? item.jssj : "" }}</uni-td></uni-tr></uni-table></view></scroll-view>
</template>
scroll-into-view需要提供滚动到的元素的id,scroll-into-view可以动态绑定id(:scroll-into-view="scrollid"
),但是滚动到元素的id不能动态绑定,所以只能通过v-if渲染这个元素
通过v-if渲染这个元素能触发滚动
<template #scroll><text id="scrollId" v-if="item.id === scrollintoid"></text>
</template>
这个元素动态绑定id不能触发滚动
<template #scroll><text :id="item.id === scrollintoid?'scrollId':''" ></text></template>
js部分
scrollintoid
变量·是用于v-if判断是否渲染滚动定位元素,scrollid
则是滚动定位元素的固定id,这两个变量最开始置空,这样能保障触发滚动效果
initData() {this.scrollintoid = "";this.scrollid = "";util.request(api.ListInfo, this.params, "GET").then((res) => {if (res.code === 0) {this.ListInfo = res.data;this.$nextTick(() => {setTimeout(() => {this.scrollid = "scrollId";this.scrollintoid = this.$store.state.scrollId;}, 50);});} else {util.showErrorToast(res.msg);}});},
行点击事件,保存点击行的id,返回页面时请求接口能触发滚动
rowClick(item) {this.$store.commit("setScrollId", item.id);uni.navigateTo({url:"/package-pc/pages/choose/choose?id=" +item.id,});},
vuex部分
import Vue from "vue";
import Vuex from "vuex";Vue.use(Vuex);const store = new Vuex.Store({state: {scrollId: "",},mutations: {setScrollId(state, id) {state.scrollId = id;},},
});
export default store;