简体   繁体   中英

Vue.js initialize object property from html

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>

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 };
        }
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM