I have created a Component that I call in a parent, but upon trying to get the value in my Component through a keypath function it is empty. Now unless I call this keypath directly in my template for the Component, it doesn't seem to exist even though its still present in the parent. Example below to illustrate this.

http://jsbin.com/golen/1/edit?html,js

有帮助吗?

解决方案

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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top