Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue component wrapping

Tags:

vue.js

vuejs2

What is the correct way to wrap a component with another component while maintaining all the functionality of the child component.

my need is to wrap my component with a container, keeping all the functionality of the child and adding a trigger when clicking on the container outside the child that would trigger the child`s onclick event,

The parent component should emit all the child component events and accept all the props the child component accepts and pass them along, all the parent does is add a clickable wrapper.

in a way im asking how to extend a component in vue...

like image 286
WalksAway Avatar asked Sep 13 '26 03:09

WalksAway


1 Answers

It is called a transparent wrapper.

That's how it is usually done:

<template>
  <div class="custom-textarea">
    <!-- Wrapped component: -->
    <textarea
      :value="value"
      v-on="listeners"
      :rows="rows"
      v-bind="attrs"
      >
    </textarea>
  </div>
</template>

<script>
export default {
  props: ['value'],  # any props you want
  inheritAttrs: false,
  computed: {
    listeners() {
      # input event has a special treatment in this example:
      const { input, ...listeners } = this.$listeners;
      return listeners;
    },
    rows() {
      return this.$attrs.rows || 3;
    },
    attrs() {
      # :rows property has a special treatment in this example:
      const { rows, ...attrs } = this.$attrs;
      return attrs;
    },
  },
  methods: {
    input(event) {
      # You can handle any events here, not just input:
      this.$emit('input', event.target.value);
    },
  }
}
</script>

Sources:

  • https://www.vuemastery.com/conferences/vueconf-us-2018/7-secret-patterns-vue-consultants-dont-want-you-to-know-chris-fritz/
  • https://zendev.com/2018/05/31/transparent-wrapper-components-in-vue.html
like image 57
sobolevn Avatar answered Sep 16 '26 06:09

sobolevn