Vue $data Object


Example

Using the $data object to change the color of a <div> element when it is clicked.

export default {
  data() {
    return {
      color: 'lightgreen'
    }
  },
  methods: {
    changeColor() {
      this.$data.color = 'pink';
    }
  }
}
Run Example »

See more examples below.


Definition and Usage

The $data object represents all the properties stored in the data part of the Vue instance.

In the example above, the color property is referred to with this.$data.color, but we can refer to the same property by just writing this.color and that is more common.

The $data object is used when we need to explicitly state that we are referring to a property in the data part of the Vue instance.

We must use the $data object if we want to refer to a data property with a name starting with "_" or "$", because in such cases the this prefix alone will not work.


More Examples

Example

Using the $data object to change the color of a <div> element every time it is clicked.

<div 
  v-on:click="$data.color+=100"
  v-bind:style="{backgroundColor:'hsl('+$data.color+',80%,80%)'}"
>
  <p>Click here</p>
</div>
Run Example »

Related Pages

Vue Tutorial: Vue v-on Directive

Vue Tutorial: Vue v-bind Directive

Vue Tutorial: Vue Methods


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.