Code Worm
Code Worm

Reputation: 323

Why watcher does not run?

I have the following data property called selector, which I set its initial value in mounted() since it is an HTML element that also has a bit of delay due to loading I set its value in a setTimeout(). Then whenever I select a different option its value should obviously change. And this change should we watched. Right now the watcher does not seem to work and I can't see why. Can someone help?

My data propery:

data() {
    return {
      selector: " ",
}}

my watcher:

watch: {
    // whenever selector changes, this function will run
    selector: function(newSelection) {
        console.log("in watcher", newSelection);
      $(".page-item a").each(function() {
        if ($(this).text() == ">") $(this).text(" ");
        else if ($(this).text() == ">>") $(this).text(" ");
        else if ($(this).text() == "<") $(this).text(" ");
        else if ($(this).text() == "<<") $(this).text(" ");
      });
    }
  },

and mounted()

 mounted() {
    setTimeout(function() {
      document
        .getElementsByTagName("select")[0]
        .setAttribute("id", "VueTables__limit");
      this.selector = document.getElementById("VueTables__limit").value;
      console.log("in mounted", this.selector);
    }, 2000);
  }

HTML:

 <div class="form-group form-inline pull-right VueTables__limit">
  <div class="VueTables__limit-field">
  <label for="VueTables__limit" class="">Records:</label> 
  <select name="limit" id="VueTables__limit" class="form-control"> 
  <option value="10">10</option>
  <option value="25">25</option>
  <option value="50">50</option></select></div></div>

Upvotes: 0

Views: 86

Answers (2)

Kaicui
Kaicui

Reputation: 3863

Update your mouted function:


mounted() {
    var self = this; //save the ref of 'this'
    setTimeout(function() {
      document
        .getElementsByTagName("select")[0]
        .setAttribute("id", "VueTables__limit");
      self.selector = document.getElementById("VueTables__limit").value;
      console.log("in mounted", this.selector);
    }, 2000);
  }

Upvotes: 1

Sergey Shapirenko
Sergey Shapirenko

Reputation: 165

First of all, if you need to setup initial data value and call some methods during component's lifecycle, use watcher with immediate: true. Next, default value could be just empty string "" no need to add space. And the last, why you use jQuery, when you have vue? Don't get it

Upvotes: 0

Related Questions