Understanding This Used in Vue.js Created

Asked 2 years ago, Updated 2 years ago, 464 views

I understand that this.interval is defined in created and the variable interval is defined, but why is this.interval when the property interval is not defined in data?

new Vue({
  el: '#app',
  created:function(){
    let that = this;
    This.interval = setInterval(function(){
      that.current=(that.current+1)%that.components.length;
    }, 3000);
    
  },
  beforeDestroy: function() {
    clearInterval (this.interval);
  },
  computed: {
    currentBanner: function() {
      return 'banner-' + this.components [this.current];
    }
  },
  data: {
    current —0,
    components: ['member', 'new', 'env']
  }
});

vue.js

2022-09-30 21:55

1 Answers

Javascript is a dynamic typing language, so you can substitute a new property for an object, even if it is a property without a declaration

The created this(variable that) becomes a Vue object, so the interval property was not added to the data.The interval property is now added to the Vue object

When Vue.js defines data, it internally generates and utilizes those getter/setter methods.The data is this.$data.Read the document to see how it works.
https://jp.vuejs.org/v2/guide/reactivity.html

The code you mentioned is a code that exchanges values through Vue objects without using data.

If you don't need reactivity, you don't have to define it in data, but I personally think it's better to define the variables used in the Vue component in data.


2022-09-30 21:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.