Vue 2.0 bind value prop to custom element

Viewed 94

I have a custom element that requires that I pass in an object as a dom property. In Vue 2 this would typically be done like

<my-element :foo.prop="{'hello': 'world'}" />

This works:

document.getElementsByTagName('my-element')[0].foo
> {hello: "world"}

But if I try to bind to the value prop:

<my-element :value.prop="{'hello': 'world'}" />

This doesn't work. Vue stringifies the object.

document.getElementsByTagName('my-element')[0].value
> "[object Object]"

Of course I can get around this by just using a ref, but this should work, right?

https://codepen.io/rhotzq2/pen/MWbOvWo

1 Answers

Vue treats value as a special key that is expected to be a string only (with the exception of <progress> elements). Therefore, the binding value is automatically stringified, and I don't see a workaround for it with normal bindings.

However, you could create a custom binding directive that binds value as an object:

new Vue({
  el: '#app',
  directives: {
    value: {
      inserted(el, binding) {
        el.value = binding.value
      }
    }
  },
})

Then use it in your template with v-value="{...}" (instead of :value="{...}"):

<my-element v-value="{'hello': 'world'}">

demo

Related