我创建了一个在父级中调用的组件,但是在尝试通过 keypath 函数获取组件中的值时,它是空的。现在,除非我直接在组件的模板中调用此键路径,否则即使它仍然存在于父级中,它似乎也不存在。下面的例子来说明这一点。
1 回答
What's happening is that this
is the component:
<p>Date: {{ startTime(this) }}</p>
refers to the default context in the ticket component (a component gets its own data content), not the context in the tickets component.
A component will, however, go looking for properties it can't find in it's context in the parent's context (unless isolated: true
has been set on the component, in which case it won't leave it's context). When it finds those properties, it "borrows" them in its own context (keeping everything in sync), which you can see by adding {{JSON.stringify(.)}}
to the ticket component:
> Object {title: "1st Release", price: "10.00", startTime: function}
So one easy fix is just to use the sale_start
property directly in the component:
<p>Date: {{ startTime(sale_start) }}</p>
or if you prefer you can just access the data in the function:
startTime: function () {
return this.get('sale_start');
}
An advantage of passing in the property, or using the get
syntax, is that you'll get auto updates on the property. Passing in the context this
and calling this.sale_start
won't give you automatic updates should the value of sale_start
change.
If you use a computed property:
computed: {
startTime: 'humaneDate(${sale_start})'
}
You can refer to it in your template as a property instead of a function:
<p>Date: {{ startTime }}</p>
The other option is to bring the whole ticket data object into the component context by declaring it explicitly as a parameter:
<ticket ticket="{{.}}"/>
This can be advantageous if you need to heavily manipulate the object in the component, versus formatting and displaying a few properties. Just remember that this change creates a ticket
property on the ticket component data context, so it can be convenient to create a block for ticket:
{{#ticket}}
<div class="ticket">
<p>Title: {{ title }}</p>
<p>Price: {{ price }}</p>
<p>Date: {{ startTime(.) }}</p>
</div>
{{/}}
Though it will work fine to just use (assuming you use the sale_start
or ticket.sale_start
in the startTime function:
<div class="ticket">
<p>Title: {{ title }}</p>
<p>Price: {{ price }}</p>
<p>Date: {{ startTime(sale_start) }}</p>
</div>