Home > Software engineering >  Why do these Vue props fail outside the main component?
Why do these Vue props fail outside the main component?

Time:04-08

I am working on a Vue 3 app. I have run into a problem working with a <Navbar /> component and one of its sub-components.

In App.vue:

<template>
  <Navbar />
  <Content title="Home" />
  <Footer />
</template>

<script>
import Navbar from './components/Navbar.vue'
import Content from './components/Content.vue'
import Footer from './components/Footer.vue'

export default {
  name: 'App',
  components: {
    Navbar,
    Content,
    Footer
  }
}
</script>

Within the Content.vue component, I can display the title this way:

<h1>{{ title }}</h1>

<script>
export default {
  name: 'Content',
  props: {
    title: String
  }
}
</script>

But displaying buttons with their labels by the same pattern as above does not work:

// Button.vue component

<template>
  <button >
    {{ label }}
  </button>
</template>

<script>
export default {
  name: 'Button',
  props: {
    label: String
  }
}
</script>


// Navbar.vue component

<template>
    <div >
        <Button label="Button 1" />
        <Button label="Button 2" />
    </div>
</template>

<script>
import Button from './Button'
export default {
  name: 'Navbar',
  components: {
    Button
  }
}
</script>

The problem

As a result of the code above, inside <div > there is only one button with no label, instead of 2 buttons labeled "Button 1" and "Button 2".

Where is my mistake?

CodePudding user response:

I think that naming your component just as the already existing HTML element is not a good idea. Try changing it to MyButton and use <my-button>... in the navbar component (you still want to use <button> in MyButton, as you want to build upon it).

Most probably browser still picks just a default button instead of yours.

The first essential rule mentioned in Vue docs is Use multi-word component names.

CodePudding user response:

You need to bind them so :label="button 1"

  • Related