`How apply multiple event on single button?`

Viewed 85

How apply multiple event on single button in Vue.js?

I have a single button component

When a button is clicked in parent, several events are must be applied

  1. tytle should change from "Buy" to "In a basket"
  2. icon shold apply done
  3. style should change to button_1

my button component

<template>
  <div class="btn"
       @click="click"
       :class="className">
    <i class="material-icons"> {{ icon }} </i>

      <span> {{ title }} </span>

  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: 'Buy'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    button_1: {
      type: Boolean,
      default: false
    },
    icon: {
      type: String,
      default: ''
    },
  },
  data() {
    return {}
  },
  computed: {
    className() {
      return {
        'btn__disabled': this.disabled,
        'btn__button_1': this.button_1,
      }
    }
  },
  methods: {
    click() {
      this.$emit('click')
    }
  },
  name: "BaseButton"
}
</script>

<style lang="scss" scoped>

.material-icons {
  font-size: 16px;
}
.btn {
  position: relative;
  font-family: 'Merriweather', sans-serif;
  color: var(--color-primary-light);
  left: 45%;
  bottom: 18%;
  height: 48px;
  width: 122px;
  cursor: pointer;
  background-color: var(--color-grey-light-4);
  display: flex;
  justify-content: space-evenly;
  align-items: center;

  &:hover,
  &:active {
    background-color: var(--color-grey-light-2);
    border: none;
  }

  &__button_1 {
    color: var(--color-primary-light);
    background-color: var(--color-grey-light-3);
    border: none;
  }
  &__disabled {
    background-color: var(--color-grey-light-1);
    border: none;
    pointer-events: none;
  }
}
</style>

my parent component

<template>
<base-button @click="clickBtn"></base-button>
</template>

<script>
import BaseButton from '../components/ui/BaseButton'
export default {
  name: "GalleryOverview",
  components: {BaseButton},
    methods: {
      clickBtn() {
        console.log('BTN clicked')
      }
    }
  }
}
</script>

How can I apply multiple event on single button?

1 Answers

You are almost done, as you are sending emit to parent component, you can use that to change.

So, first you will need to pass the required props to the child component, as:

<template>
<base-button @click="clickBtn" :title="title" :icon="icon" :button_1="button_1"></base-button>
</template>

<script>
import BaseButton from '../components/ui/BaseButton'
export default {
  name: "GalleryOverview",
  data() {
    return {
      title: 'My Title',
      icon: '',
      button_1: false
    }
  }
  methods: {
    // This is where you can change.
    clickBtn() {
      this.icon = 'change icon';
      this.title = 'change title';
      this.button_1 = true;
    }
  }
}
</script>

Now when you click the button it will change the title, icon and button_1.

Related