Search code examples
javascriptangularvue.jsweb-component

Vuejs: Can't pass object to web component using v-bind


I have a web component built with Stencil that I imported into a Vue project. The component takes in an object as a prop. When I pass the object using v-bind, it doesn't work. When I pass it using ref in JavaScript, then it works.

For example, this does not set my property:

<my-web-component :my-object="myObject" />

But this does:

<template>
  <my-web-component ref="myObjectRef" />
</template>
<script>
export default {
  //...
  mounted() {
   this.$refs.myObjectRef.myObject = myObject // <-- this works
  }
}
</script>

When I use the web component in Angular, it works using @Input as usual.

What's the reason that the prop works in Angular, but in Vue I have to assign it in JavaScript?


Solution

  • v-bind assumes an attribute if it can't determine that the target is a property, which would be the case for Stencil components. You'll notice the attribute bound as a generic string (i.e., [object Object]) in the DOM when inspecting the component:

    screenshot of inspection

    To bind to the Stencil component's property in a Vue 2 template, use v-bind's .prop modifier:

    <my-web-component :my-object.prop="myObject" />
                                ^^^^^
    

    Alternatively, use v-bind's object syntax (works in Vue 2 and Vue 3):

    <my-web-component v-bind="{ myObject }" />
    

    Vue 3 demo