Javascript VueJS 获取数据作为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46091418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:20:05  来源:igfitidea点击:

VueJS get data as object

javascriptvue.jsvuejs2vue-component

提问by rap-2-h

Here is a VueJS component:

这是一个 VueJS 组件:

<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 datafrom the logfunction and get it as an object (just like in its declaration). I know I can get data like this :

我想datalog函数中访问并将其作为对象获取(就像在其声明中一样)。我知道我可以得到这样的数据:

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?

有没有办法在组件的方法中获取整个数据对象?

回答by Shubham Patel

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

您可以使用 访问当前组件的数据对象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);
}

回答by cornernote

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

我认为您正在寻找的是返回整个数据对象,如下所示:

log() {
  console.log(this.$data);
}