operating environment
Vue3
Element Plus
problem reproduction
<template>
<el-tree
ref="treeRef"
:data="data"
/>
</template>
<script lang="ts" setup>
// 引入必要组件
getTreeData()
.then((res) => {
data.value = res.data
treeRef.value.setChecked();
})
</script>
I wanted to set the selected value when assigning a value to the tree component, but it did not take effect, so I tested it and found that treeRef.value.data is empty, that is, the tree component at this time is still the component before the assignment, yes Not really, you can use the onUpdated test, you can get the data value under onUpdated, but can you only perform follow-up operations in onUpdated? In fact, there is an easier way
Solution
<template>
<el-tree
ref="treeRef"
:data="data"
/>
</template>
<script lang="ts" setup>
// 引入必要组件
getTreeData()
.then((res) => {
data.value = res.data
}).finally(() => {
treeRef.value.setChecked();
})
</script>
Although the operation cannot be performed in then, then in finally, after the then completes the operation, it will enter finally. At this time, the dom has been updated, and the updated dom is obtained in finally, and the next step can be performed at this time.