Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push not updating array in DOM Vue

Tags:

dom

vue.js

axios

I am using Vue and am trying to make live search. But on updating the content of search, it doesn't get updated.

Data do get update in array, when checked in dev tools. But DOM don't get updated.

template

<div class="dropdown">
    <input type="text" v-model="input" placeholder="Search" @keyup="searching" data-toggle="dropdown">
    <span class="caret"></span>
    <ul class="dropdown-menu">
      <li v-for="(data,index) in availSearchData" :key="index">
        <a href="#">{{data.name}}</a>
      </li>
    </ul>
  </div>

method

searching() {
  if (this.input) {
    let url = this.domain + "search";
    axios
      .get(url, {
        params: {
          table: this.table,
          data: this.input
        }
      })
      .then(res => {
        this.availSearchData = [];
        res.data.forEach(doc => {
          this.availSearchData.push(doc);
        });
      });
  }
}

I don't know where I am doing wrong. Please help out if possible.

like image 614
user11024704 Avatar asked Mar 13 '19 15:03

user11024704


People also ask

How does Vue update the DOM?

Vue. js uses a reconciliation technique to update the real DOM.

How do I Rerender components in Vue?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.

What updates the virtual Dom in Vue?

Virtual DOM in Vue is a JavaScript object that represents the Document Object Model (DOM). The application updates the Virtual DOM instead of the DOM directly.

Can I use DOM in Vue?

If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance. You can also access the DOM element directly; it is a read-only attribute and returns an object.


1 Answers

To add an item to the back of an array and get it to be reactive in Vue, below is what worked for me:

this.$set(this.items, 
          this.items.length, 
          JSON.parse(JSON.stringify(this.item))
         );

The this.$set is Vue's inbuilt array manipulation function that guarantees reactivity. The this.items is the array, this.items.length (NOTE: it is items.length NOT items.length - 1) is to push a new index to the back of the array and finally, JSON.parse(JSON.stringify(this.item)) is to clone the this.item into a new object before pushing into the array. The cloning part may not be applicable to you and I used this in variables because all the variables are declared in my data() function.

like image 141
Tunde Michael Avatar answered Oct 23 '22 09:10

Tunde Michael