Search code examples
vue.jsvuejs3vue-componentvue-composition-api

How to bind on a prop of type object using v-bind


referring to this link i am trying to implement the example shown in section titled Binding Multiple Properties Using an Object.

i have the following object in the parent compoent:

const post = {
  id: 1,
  title: 'My Journey with Vue'
}

and i want to pass it to the child component using v-bind, so i coded the parent component as shown below in the code, ans the child component is as shown below as well. the problem is, at the run time, the {{ post }} in the child-component is empty.

please let me know how can i canonically bing on properties using v-bind

note:

i know how to bind on props of a child-component, as shown in the follwoing example:

    **parent-component**:
        <component :is="HelloWorld" :msg="m" :id="posts.id" :title="posts.title"/>
    **child-component**:
        <template>
          <div class="hello">
            msg:{{msg}}
            <br/>
            postId:{{id}}
            <br/>
            postTitle:{{title}}             
          </div>
        </template>
        

parent.vue:

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <component :is="HelloWorld" :msg="m" v-bind="post"/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<script setup>
import { ref } from 'vue'

const post = {
  id: 1,
  title: 'My Journey with Vue'
}
</script>   

child-component:

<template>
  <div class="hello">
    msg:{{msg}}
    <br/>
    posts:{{post}}
    
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    post:Object,
  }
}
</script>

Solution

  • If you want to use v-bind="someObject", its properties will be destructed and you should have that properties defined as props in child component :

    Child :

    <template>
      <div class="hello">
        msg:{{msg}}
        <br/>
        post title:{{title}}
        
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      props: {
        msg: String,
        id: String,
        title : String
      }
    }
    </script>