0

How can I set a composed property (like composed_prop.foo) from HTML?

The normal_prop sets well but composed_prop.foo doesn't.

Example:

<div id="app">
      <sample normal_prop=1 composed_prop.foo=1 />
</div>


<script>

    Vue.component('sample',{
      props: {
        normal_prop: 0,

        composed_prop: {
            default:{
               foo: 0,
               bar: 0
            }
        }
      }
    })


    new Vue({
        el: "#app"
    })
</script>

1 Answer 1

2

You have to do it like this:

<div id="app">
     <sample normal_prop=1 :composed_prop="{foo:10, bar:20}" />
</div>

Note that you have to bind the composed_prop so the expression will be evaluated (rather than treating it as a literal string). Also note that passing in an object for composed_prop will completely overwrite your defaults - it won't try to merge the properties with the defaults. So, if you only pass in {foo:10}, then composed_prop.bar will be undefined.

One final note... I think the default for an Object prop should be a factory function. Something like this:

Vue.component('sample',{
  props: {
    normal_prop: 0,

    composed_prop: {
        type: Object,
        default:function(){ // should be a function
            return { foo: 0, bar: 0 };
        }
    }
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, it's working. Thank you very much for your awesome response and that note about the factory function, I noticed the warning, but didn't know what to do about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.