尝试写一下vue3 element-plus的table,总数:data绑定数据时不成功。经过几个小时的推敲和尝试,总算是发现了哪里的问题。
先看代码
<el-table :data="rolesList.list" :max-height="tableMinHeight()" ref="rolesListRef" v-loading="loading" style="width: 100%; margin-top: 30px" border > <el-table-column align="center" Prop="RoleKey" label="角色key" width="220" > <template #default="scope"> {{ scope.row.roleKey }} </template> </el-table-column> <el-table-column align="center" label="角色名称" width="220"> <template #default="scope"> {{ scope.row.name }} </template> </el-table-column> <el-table-column align="header-center" label="角色描述"> <template #default="scope"> {{ scope.row.description }} </template> </el-table-column> <el-table-column align="header-center" label="创建时间"> <template #default="scope"> {{ scope.row.createTime }} </template> </el-table-column> <el-table-column align="center" label="操作"> <template #default="scope"> <el-button type="primary" size="small" @click="handleEdit(scope)" >编辑</el-button > <el-button type="danger" size="small" @click="handleDelete(scope)" >删除</el-button > </template> </el-table-column> </el-table>
<script lang="ts">import { defineComponent, onMounted, ref, reactive } from "vue";import { getRolesList } from "@/api/roles";interface role { Id: number; RoleKey: string; Name: string; Description: string; Routes: string; CreateTime: number; UpdateTime: number;}export default defineComponent({ name: "role", setup() { const rolesList: { list: role[] } = reactive({ list: [] }); const loading = ref(true); async function getList() { const res = await getRolesList(); rolesList.list = res.data; loading.value = false; } onMounted(() => { getList(); }); const tableMinHeight = () => { return window.innerHeight - 156; }; return { rolesList, loading, tableMinHeight, rolesListRef, }; },});</script>
这么写总是提示 Property "list" was accessed during render but is not defined on instance.
字面意思是:data="rolesList.list"中的list没有被定义。
最初是考虑生命周期的问题,结果尝试了一遍也没解决,后来觉得是组件绑定api没有深度绑定的问题,但是reactive官方文档上就写了说是深度的,总之尝试了torefs,unrefs等api,还是没解决。
github上目前有的项目里,我看写法是跟我一样的,但是就是不成功。
尝试循环了个div,调用rolesList.list,发现是成功的。这就奇怪了。
后来突然想,el-table的ref没有绑定,于是在setup里写了个
const rolesListRef = ref()
然后,成功了!!!!
研究发现,你在dom里写了ref="xxx"就需要在setup中写一个对应,否则数据绑定不成功。