Skip an object as a reference to Vue

How do you keep passing objects as props to vue? I would suggest that this will be a simple task, but apparently not.

I have the following code in a .vue file:

`

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

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

`

In html, I am trying to pass the details dataas follows:

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

When I try to enter the console, the result will be only an empty observer object.

+4
source share
2 answers

I believe the problem is elsewhere in your code, since passing an object as a support 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:

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

Here is a fiddle showing this in action: https://jsfiddle.net/tk9omyae/

+4
source

: 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>

HTML:

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

JsFiddle, : https://jsfiddle.net/mqkpocjh/

0

Source: https://habr.com/ru/post/1685034/


All Articles