[英]Vue.js initialize object property from html
How can I set a composed property (like composed_prop.foo
) from HTML? 如何从HTML设置一个组合属性(如
composed_prop.foo
)?
The normal_prop sets well but composed_prop.foo doesn't. normal_prop设置得很好,但是composed_prop.foo设置得不好。
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). 注意,您必须绑定composed_prop,以便对表达式进行求值(而不是将其视为文字字符串)。 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.
还要注意,为composited_prop传入一个对象将完全覆盖您的默认设置-它不会尝试将属性与默认设置合并。 So, if you only pass in
{foo:10}
, then composed_prop.bar
will be undefined. 因此,如果您仅传递
{foo:10}
,那么composed_prop.bar
将是未定义的。
One final note... I think the default for an Object prop should be a factory function. 最后一点...我认为Object属性的默认值应该是工厂函数。 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 };
}
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.