What is the reason behind why modifying data in beforeCreated/created/beforeMount does not activate watch in VUE?

Why is it that modifying data in beforeCreated/created/beforeMount does not activate the watch function in Vue?

<template>
  <div>
    <titi :namer="parentName"></titi>
  </div>
</template>

<script>
export default {
  components: {
    titi: {
      template: "<h1>{{namer}}</h1>",
      props: ["namer"],
      watch: {
        namer: {
          immediate: false,
          handler(val, oldVal) {
            console.log("jackieyin", val);
          }
        }
      },
      mounted() {
        console.log("jackieyin", "mounted");
      }
    }
  },
  data: function() {
    return {
      parentName: "jackieyin"
    };
  },
  beforeCreate() {
    console.log(222);
    this.parentName = "sunwukong";
  },
  created() {
    this.parentName = "kewu";
  },
  beforeMount() {
    this.parentName = "tangseng";
  },
  mounted() {
    // var that = this;
    // this.parentName = "tyty";
    // setTimeout(() => {
    //   that.parentName = "shaseng";
    // }, 500);
  }
};
</script>

Despite my attempts to modify the data during these lifecycle stages, the child element's props watch function remains inactive. Feel free to experiment with it here: https://codesandbox.io/s/vue-watch-inx4z

Answer №1

As anticipated, the behavior aligns with expectations. The life cycle sequence outlined below illustrates that on the parent component, child components are only created after the beforeMount phase of the parent and before the mounted phase of the parent. Therefore, any watches set on the child will not trigger for changes to props made in the parent's beforeCreate or created phases because the child does not exist at that point.

  • Parent beforeCreate
  • Parent created
  • Parent beforeMount
    • Child beforeCreate
      • The child watcher will activate here if immediate: true, and pass the initial value
    • Child created
    • Child beforeMount
    • Child mounted
  • Any changes to the property will trigger the child watcher from this point onward
  • Parent mounted

In your watcher, you have set the value immediate: false. This implies that it will not activate when the initial value for the property is set. If you change this to true, you will observe that the value set by the parent in the beforeMount phase will immediately trigger the watch when the child component is created. Furthermore, if you modify the value again in the parent's mounted phase, the child's watcher will detect this regardless of the immediate setting.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Unclear on the usage of "this" in arrow functions?

After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this in arrow functions. I've been encountering run-time errors with a code snippet similar to the following: export class Foo imp ...

Using jQuery within an Angular Controller: The specific function $(...).overhang is not recognized in this context

Recently, I decided to integrate overhang.js into my application because of its appealing alert messages. Initially, it seemed like a simple task... All I needed to do (or so I thought) was replace the line in my controller, alert("An HTTP request has be ...

Ways to evaluate negative numbers in JavaScript

I need to validate latitude and longitude values within the range of -180 to 180. If a number falls outside of this range, an error should be displayed. Below is the code I have written for this validation: if((markerPoint[0] && parseInt(markerPoint[0] ...

Is having an excessive amount of reactive data in Vue.js detrimental to app speed and overall performance?

Our team is currently in the process of developing a highly intricate single page application similar to Excel using vue.js. This project consists of over 10,000 components, with each cell functioning as an individual component containing approximately 100 ...

Error: Unexpected character 'o' encountered in AngularJS syntax

Whenever I try to call this controller, it gives me an error. hiren.controller('hirenz' , function($scope , $http , $location , $routeParams){ $http.post((rootURL + "music") , {'alpha' : $routeParams.alpha , 'name' : $rou ...

Transmit information using $broadcast when a button is clicked, and retrieve that information using $scope.$on

I am trying to create a function that will broadcast data from the server upon button click, and then navigate to a new route using $state.go('new-route'). In the controller of this new state, I want to retrieve the transmitted data. However, whe ...

Tips for bringing in a local dependency using yarn

I currently have 2 ongoing projects: ProjectA: a front-end project built with Vue.js ProjectB: a JavaScript module that I intend to use as a library in Project A I successfully built ProjectB and proceeded to run yarn link In the package.json file of P ...

Can you achieve a click event in Vue without using $refs?

I have a template structured as follows: <p @click="handleParagraphClick"> <component v-for="item in items" :is="spanComponent"/> </p> The template for the nested span component looks like this: <span ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Access the data from a JSON object within a v-select menu

<v-form :model='management'> <v-flex xs3 sm2 md3> <div class="form-group> <v-select :items="days" item-text='text' item-value='text' placeholder="MM" single-line attach v- ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

Vue.js HTTP POST request not correctly sending object data

I created a Vue.js App that looks like this var vueCommentApp = new Vue({ el: '#Commentdiv', data: { newComment:{"userCommentID":0,"siteurlID":1,"userId":"","userName":"Guest","commentPageT ...

How many addresses are stored in the JSON file?

After verifying the JSON data and trying to determine the number of addresses, I encountered the following result when accessing the information: var location = req.body; The output obtained was: { AddressValidateRequest: { '-USERID': &ap ...

What is the most efficient method to determine the most recent update to a MongoDB document?

Is it necessary for me to add lastActivity: new Date() @set every time I use it, or is there a more efficient method? ...

identifying the element targeted on dynamically created links with the help of jquery

I have created dynamic links where clicking on a country link displays the cities of that particular country. I am trying to retrieve the event.target.id of the dynamically generated city link when it is clicked. $(".countryName").children().on('cl ...

Unchecking the select-all checkbox in Ag-Grid after updating the row data using an external button

In my ag-grid setup, I have implemented checkboxes in the first row to allow users to select individual rows. Additionally, there is a "select all" checkbox in the header for easy selection of all rows with a single click. To create the select all checkbox ...

The paragraph tag remains unchanged

I am currently working on developing a feature that saves high scores using local storage. The project I'm working on is a quiz application which displays the top 5 scores at the end, regardless of whether the quiz was completed or not. However, I&apo ...

Solving Problems with D3 Bar Charts

I currently have a database structured with 5 columns: ID, customerName, dateYear, dateMonth, and dateDay. The date information is added to the database when a user submits a form. For example, if a user submits a form today, the 3 date columns would refle ...

Test your knowledge of Javascript with this innerHtml quiz and see

How can I display the output of a score from a three button radio button quiz without using an alert popup? I want the output to be displayed within a modal for a cleaner look. I tried using InnerHTML but now there is no output when the button is clicked. ...