Javascript 在 Vue 上将对象作为道具传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46041825/
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:18:48  来源:igfitidea点击:

Pass object as prop on Vue

javascriptvue.js

提问by Diego Gallegos

How do you go on passing objects as props on vue? I would imagine this would be a simple task but apparently not.

你如何继续在 vue 上将对象作为道具传递?我想这将是一项简单的任务,但显然不是。

I have the following code on a .vue file:

我在 .vue 文件中有以下代码:

`

`

<template>
    <div id="scatter"></div>
</template>

<script>
    export default {
       props: {
           data: {
                type: Object,
           default: () => ({})
       }
     },
     mounted () { 
         console.log(this.data)
     }
    }
</script>

`

`

On html I try to pass the dataprops as follows :

在 html 上,我尝试data按如下方式传递道具:

<component :data="{x:1}"></component>

<component :data="{x:1}"></component>

When I try lo log it into the console the result is only an empty observer object.

当我尝试将其登录到控制台时,结果只是一个空的观察者对象。

回答by Jamie Curnow

I believe the problem is somewhere else in your code as passing an object as a prop is as simple as you imagine:

我相信问题出在您的代码中的其他地方,因为将对象作为道具传递就像您想象的一样简单:

// register the component
Vue.component('component', {
  props: {
    data: {
        type: Object
    }
  },
  template: '<div>Data: {{data}}</div>',
  mounted: function () {
    console.log(this.data)
  }
})

new Vue({
  el: '#example'
})

HTML:

HTML:

<div id="example">
  <component :data="{x:1}"></component>
</div>

Here's a fiddle showing it in action: https://jsfiddle.net/tk9omyae/

这是一个显示它在行动中的小提琴:https: //jsfiddle.net/tk9omyae/

回答by kushalvm

v-bind="yourObject"

Should do on <my-component v-bind="yourObject"><my-component>

应该做 <my-component v-bind="yourObject"><my-component>

Not sure about <component></component>. Still digging into Vue. Try and let us know.

不确定<component></component>。仍在深入研究 Vue。尝试让我们知道。

回答by exclsr

Edit: After my initial answer and creating a JsFiddle, I am not sure why the behavior you described is happening. It works when narrowed down to the use case:

编辑:在我最初的回答并创建一个 JsFiddle 之后,我不确定为什么你描述的行为正在发生。当缩小到用例时,它可以工作:

<script>
    export default {
       props: {
           ok: {
               type: Object,
               default: () => ({}),
           },
           data: {
               type: Object,
               default: () => ({})
           }
       }
     },
     mounted () { 
         console.log(this.data) // {x:1}
         console.log(this.ok) // {x:1}
     }
    }
</script>

And the HTML:

和 HTML:

<component :ok="{x:1}" :data="{x:1}"></component>

Here is a JsFiddle that demonstrates the behavior: https://jsfiddle.net/mqkpocjh/

这是一个演示行为的 JsFiddle:https://jsfiddle.net/mqkpocjh/