Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS get data as object

Here is a VueJS component:

<template>
  <a @click="log">click me<a>
</template>

<script>
  export default {
    data() {
      return {
        a: "a",
        b: "something",
        foo: { bar: "baz" },
        // etc.
      }
    },
    methods: {
      log() {
        // console.log( data ); 
        // ???
      }
    }
  }
</script>

I want to access the data from the log function and get it as an object (just like in its declaration). I know I can get data like this :

log() {
  console.log( this.a );
  console.log( this.b );
  console.log( this.foo );
}

But what I want is the whole data as an object (because I want to send the data via an event to a parent component).

Is there a way to get the whole data object inside a method of a component?

like image 947
rap-2-h Avatar asked Sep 07 '17 08:09

rap-2-h


People also ask

What does data () do in Vue?

data # A function that returns the initial reactive state for the component instance. The function is expected to return a plain JavaScript object, which will be made reactive by Vue.

Are Props reactive Vue?

Props and data are both reactiveWith Vue you don't need to think all that much about when the component will update itself and render new changes to the screen. This is because Vue is reactive. Instead of calling setState every time you want to change something, you just change the thing!


2 Answers

You can access the current component's data object using this.$data.

Reference: Link

So the log function should be like:

log() {
  console.log(this.$data.a);
  console.log(this.$data.b);
  console.log(this.$data.foo);
}
like image 66
Shubham Patel Avatar answered Oct 24 '22 06:10

Shubham Patel


I think what you are looking for is to return the whole data object, like this:

log() {
  console.log(this.$data);
}
like image 7
cornernote Avatar answered Oct 24 '22 06:10

cornernote