0

Learning Vue:

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue app</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <style>
  </style>
</head>
<body>
    <div id="app">
        <friends v-for="friend in friends" :friend="friend"></friends>
    </div>
  <script>
      Vue.component('friends', {
        props    : ['friend'],
        template : `<table>
                    <tr><td>{{ friend.fname }}</td><td>{{ friend.lname }}</td></tr>
                  </table>`,
      })

    const vm = new Vue({ 
        el   : '#app',
        data : {
            friends : [
              {fname : 'Cornelius', lname : 'Johnson'},
              {fname : 'John',      lname : 'Waybe'},
              {fname : 'Neo',       lname : 'Anderson'},
            ],
        }
    })
  </script>
</body>
</html>

This works fine but it outputs several tables vs one table and it's rows.

I tried something like this

    <div id="app">
        <friends></friends>
    </div>

 Vue.component('friends', {
        props    : ['friends'],
        template : `<table>
                    <tr v-for="friend in friends" :friend="friend"><td>{{ friend.fname }}</td><td>{{ friend.lname }}</td></tr>
                  </table>`,
      });

    const vm = new Vue({ 
        el   : '#app',
        data : {
            friends : [
              {fname : 'Cornelius', lname : 'Johnson'},
              {fname : 'John',      lname : 'Waybe'},
              {fname : 'Neo',       lname : 'Anderson'},
            ],
        }
    })

But that just outputs an empty table.

How can I output just one table and its rows?

1 Answer 1

2

You should pass friends to the friends prop =).

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue app</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <style>
  </style>
</head>
<body>
    <div id="app">
        <friends :friends="friends"></friends>
    </div>
  <script>
      Vue.component('friends', {
        props    : ['friends'],
        template : `<table>
                <tr v-for="friend in friends"><td>{{ friend.fname }}</td><td>{{ friend.lname }}</td></tr>
              </table>`,
      })

    const vm = new Vue({ 
        el   : '#app',
        data : {
            friends : [
              {fname : 'Cornelius', lname : 'Johnson'},
              {fname : 'John',      lname : 'Waybe'},
              {fname : 'Neo',       lname : 'Anderson'},
            ],
        }
    })
  </script>
</body>
</html>

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

1 Comment

In this case no. The friends data is outside the component so you have to pass to the friends component via props

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.