Chris Rockwell
Chris Rockwell

Reputation: 1852

Show string in component

I am trying to learn Vue.js, and am playing around with the modal component example. I'm trying to change it up a bit so that the button clicked can provide data to the component (I'm very new to this so my terminology may be off).

I've updated the app to be:

// start app
var app = new Vue({
  el: '#app',
  data: {
    showModal: false,
    title: 'Default Title'
  },
  methods: {
    modalInit: function(title) {
      //this.title = title;
      this.showModal = true;
    }
  }
})

The updates were mainly so that I can change the title within the modal based on the button clicked, here is the update to the button:

<button id="show-modal"@click="modalInit('A title')">Show Modal</button>

The relevant portion of the x-template:

<div class="modal-header">
  <h2>{{ title }}</h2>
</div>

Not sure if it matters, but the component is:

Vue.component('modal', {
  template: '#modal-template',
})

In this state, the modal will open fine but the title won't be there and I get the console error: [Vue warn]: Property or method "title" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

I can't figure out to to properly "declare reactive data properties in the data option".

Thanks!

Upvotes: 0

Views: 107

Answers (1)

thanksd
thanksd

Reputation: 55664

You've specified a title property for the root component. But, the modal component does not have a title property. Add it like this:

Vue.component('modal', {
  template: '#modal-template',
  data() {
    return {
      title: "Default Title"
    }
  }
})

If you want to pass in a dynamic value for title, make it a property instead:

Vue.component('modal', {
  template: '#modal-template',
  props: ['title']
})

Then, you can pass the value for the title in the component tag:

<modal :title="dynamicTitle"></modal>

Upvotes: 1

Related Questions