Home > Software engineering >  VueJS - reference a prop in a component?
VueJS - reference a prop in a component?

Time:06-24

Looking to implement a component and on a click event I want to reference a prop in a method. A simple example:

<template>
  <div >
    <span>Hi!</span>
    <button
      
      @click.stop="clicked"
    >{{notificationTitle}}</button>
  </div>
</template>

<script>
export default {
  name: 'Toastification',
  props: {
    notificationTitle: {
      type: String,
    },
    notificationID: {
      type: String,
    }

  },
  methods: {
    clicked() {
      this.$emit('eventName', this.notificationID)
    }
  }
};
</script>

This may not be the production version, it is just an example. I can access a prop in the Template part using {{}}, but in the method using this.notificationID fails - how do I correctly reference notificationID?

Thanks

CodePudding user response:

OK, when I read through the code, so obvious! Pass in the prop to the method call:

 @click.stop="clicked(notificationSetID)"


then:
clicked(notificationSetID) {
    console.log(notificationSetID)
}

CodePudding user response:

You code looks perfect and it should work. Here, I just creating a working Demo. Please have a look and let me know if you faced any challenge.

Vue.component('child', {
  props: ['notificationtitle', 'notificationid'],
  template: `<div >
    <span>Hi!</span>
    <button
      
      @click.stop="clicked"
    >{{ notificationtitle }}</button>
  </div>`,
  methods: {
    clicked() {
      console.log(this.notificationid);
    }
  }
});

var app = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child notificationTitle="Hello Vue !" notificationID="1">
  </child>
</div>

  • Related