0

I have been trying to learn Vue and can't get props working correctly. Props I pass in continue to be undefined and I can't seem to figure out why

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>
  <title>Document</title>
</head>
<body>
  <div amount = "5" id="app" @click="console.log('clicked')">
      <p>{{amount}}</p>
      <span >{{message}}</span>
    </div>
  <script>
    var test = new Vue({
      el: '#app',
      props: ['amount'],
      data: {
        message: 'Hello World',
      },
      created: function() {
            console.log(this.amount)
        },
    });
  </script>
</body>
</html>

This is the code I was trying to work with previously to isolate the issue to figure out why the props are coming through as undefined, but it still isn't working. Can someone help me figure out how you are supposed to do this?

jonlev03
  • 35
  • 5

1 Answers1

0

Props and listeners like your @click is part of Vue. Not HTML.

The Vue app is being rendered into div#app. That means that amount=5 and @click is outside of Vue app.

Your amount prop is undefined because you didn't pass it at all.

Try this: demo

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>
</head>
<body>
<div id="app"></div>
  <script>
    var TestComponent = {
      props: ['amount'],
      created: function() {
        console.log(this.amount)
      },
      methods: {
        log() {
          console.log('clicked')
        }
      },
      template: '<p @click="log">{{ amount }}</p>'
    }
    
    var test = new Vue({
      el: '#app',
      components: { TestComponent },
      data: {
        message: 'Hello World',
      },
      template: `
        <div>
          <span>{{message}}</span>
          <test-component amount="5" />
        </div>
      `
    });
  </script>
</body>
</html>
Adam Orłowski
  • 4,268
  • 24
  • 33