search

Home  >  Q&A  >  body text

javascript - Vue deletes array elements causing remaining elements not to be re-rendered

I have recently used Vue in a project, but during the development process I discovered that when I delete an element in the array, the elements behind the element will not be re-rendered.

The html code is as follows:
There are two components: one is the Main component, used to contain all content containers; the other is the sub-component, used to display content.

js code is as follows:

Then there is also a Vuex store:

Normally speaking, when deleting a sub-container, you should be able to directly use splice, the overridden method of arrays in vue, to delete it.
like:

   state.Content.splice(i,1);

But after using it, I found that after deleting an element, the elements behind this element will be reloaded and not re-rendered, and the vue logic in the page is not executed normally.

After trying various methods, there is still no solution. It seems that when the element is deleted, the subscript of the subsequent element changes, causing the content in the element to be reloaded but not rendered.

So my final solution was, as shown in the picture above, not to delete the element directly, but to use

state.Content.splice(i,1,null);

The

method sets the elements in the array to empty without changing the arrangement of the array, thus ultimately solving the problem.
But this solution can only treat the symptoms but not the root cause, and cannot answer my questions very well.
So I would like to ask all the experts, Is there any better way to solve it?

女神的闺蜜爱上我女神的闺蜜爱上我2723 days ago1102

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:31:02

    You try to clone the array, and then after operating in this array, assign this array to the previous one. This will definitely trigger Vue to re-render.

    PS: By the way, whether Vue will re-render depends on whether the dependent data has changed. So, if you use ordinary methods to add or delete reference type data (Array, Object...), Vue may not Changes in data are detected. So, you use the method I mentioned above (simple and crude), or use methods such as this.$set... provided by Vue.

    reply
    0
  • 滿天的星座

    滿天的星座2017-06-12 09:31:02

    When you delete it, you can try to reassign state.Content
    I usually do this
    state.content = state.content.map( e=> {

    if(e.id !==x) return e 

    })

    reply
    0
  • Cancelreply