1

I have a fairly simple setup which is failing with these errors:

Property or method "fruit" is not defined on the instance but referenced during render. Make sure that this property is reactive [etc.]

Error in render: "TypeError: Cannot read property 'name' of undefined"

Cannot read property 'name' of undefined

Not sure whether it's because the x-template referencing method is buggy. I see it's not used much.

Here's my code:

<div id="main">

  <h1>Vue Component Prop Error</h1>

    <script type="text/x-template" id="foo">
      <p>{{fruit.name}}</p>
    </script>

    <my-thing :fruit="fruits[1]"></my-thing>

</div>

<script>
    Vue.component('my-thing', {
      template: '#foo',
      props: {
        fruit: Object
      }
    });

    var app = new Vue({
      el: '#main',
      data: {
        fruits: [{
            id: 1,
            name: 'apple'
        },{
            id: 2,
            name: 'banana'
        },{
            id: 3,
            name: 'carrot'
        }]
      }
    })
</script>

What am I missing? (I'd expect to see "banana" on the screen.)

Codepen: https://codepen.io/MSCAU/pen/WagOjz

2 Answers 2

3

Move the x-template out of the div that the main Vue instance controls:

<div id="main">

  <h1>Vue Component Prop Error</h1>

  <my-thing :fruit="fruits[1]"></my-thing>

</div>

<script type="text/x-template" id="foo">
  <p>{{fruit.name}}</p>
</script>

https://codepen.io/anon/pen/zmJzJO

Sign up to request clarification or add additional context in comments.

Comments

1

Having the template inside of #main is causing Vue to try to render it prior to when you want.

Moving the template outside of #main will allow it to be used as the template for <my-thing> without being rendered inside of #main.

<div id="main">
    <my-thing :fruit="fruits[1]"></my-thing>
</div>
<script type="text/x-template" id="foo">
  <p>{{fruit.name}}</p>
</script>

https://codepen.io/anon/pen/NOLgBz

2 Comments

Two good answers at the same time. This works, thanks. Now where on earth is this documented? Not mentioned here: vuejs.org/v2/guide/components-edge-cases.html#Inline-Templates
Good question, not sure if this specifically is documented. It's just something I know from experience and something you should expect. You set your 'el' as '#main'. So anything inside of #main will be rendered with the app scope. app doesn't know you've defined that block as a template for <my-thing> or that it shouldn't try to evaluate {{ fruit.name }}.

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.