简体   繁体   中英

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');
   }

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM