fetixzz
fetixzz

Reputation: 87

How to use watch in vuejs?

I have this code and can't understand what problem is. Watch doesn't work when I add a new ticker, it works only when I reload page

addClick() {
  const currentTicker = {
    name: this.ticker,
    price: "25",
  };

  if (!this.namesT.includes(currentTicker.name.toUpperCase())) {
    this.exist = false;
    this.namesT.push(currentTicker.name.toUpperCase());
    console.log(this.namesT);
    this.tickers.push(currentTicker);
    console.log('add Ticker');
    this.updateInterval(currentTicker.name);
  } else {
    console.log("This name already exist");
    this.exist = true;
  }
watch: {
   tickers(){
     localStorage.setItem("crypto-list", JSON.stringify(this.tickers));
     localStorage.setItem("crypto-name-list", JSON.stringify(this.namesT));
     console.log('Add to localStorage');
   }

Upvotes: 0

Views: 105

Answers (1)

Mina
Mina

Reputation: 17594

You just need to update the reference of the array.

this.tickers = [...this.tickers, currentTicker]

instead of

this.tickers.push(currentTicker);

as push will add the item but will keep the same old reference.

Upvotes: 1

Related Questions