When the site owner Dotnet9 was developing the article editing and category management feature for the backend frontend, they encountered an issue with the
element-uitreecomponent. After personal attempts failed to resolve it, the following article presents a solution from a frontend expert. As for what the problem is and how it was solved, please read on. Hope it helps you all.
Main text begins
Preface: When using the tree component from element-ui, I naively thought that dynamically modifying the value of the default-checked-keys property would also change the default checked values accordingly. In reality, it does not.
Let's first look at the official definition of default-checked-keys: (Even after reading it, I still thought it should work)

So I set out to explore the reason: It listens for changes to defaultCheckedKeys, traverses the array, and adds the checked state. However, when the defaultCheckedKeys array shrinks, the previously set checked key is not removed.
The reason is: In tree.vue, the watch on the default-checked-keys value triggers the following method:

In tree-store.js, this method is used again:

Now I know the reason: Only when a change in the default-checked-keys value is detected does it traverse the default-checked-keys array and set the checked state for the values inside it, but there is no operation to remove the checked state. So when you add data that needs to be checked inside the original array of default-checked-keys, the newly added nodes will be checked, but the opposite will not happen!
What to do then??
Ideas:
- Modify the dependency code
I already mentioned this in this blog post: el-tree handling large amounts of data
- Look more carefully at the documentation for ideas; found it: call the
setCheckedKeysmethod, pass in the array ofkeyvalues that need to be checked, and it will reset the checked state:

Note when using this method:
Call it after the
treealready exists in theDOM. If thetreehas not finished loading,setCheckedKeysdoes not exist. So we need to use thethis.$nextTick(callback)method, which will execute the callback after the DOM has finished loading.After calling this method, if you are using lazy loading to load nodes, the half-checked state you manually set will disappear. Remember to reset the half-checked state.
This article is reprinted.
Author: 水星梦月
Original title: el-tree: default-checked-keys property changes do not take effect
Original link: https://blog.csdn.net/monparadis/article/details/114087838