Skip to main content

Own Subcomponent

Create your component

First, create your component. In my example, this will happen in a subfolder within my detail directory. This houses the detail component in which i want to include my new component:

  • detail
    • subcomponent
      • index.html.twig
      • index.js
    • detail.html.twig
    • detail.scss
    • index.js

Index.js

We only need a index.js and a template file. The Index JS looks like this:

import template from "./index.html.twig";

Shopware.Component.register('my-component-name', {
template,
props: {
myVariable: {required: true}
}
})

With the props bit we allow the component to "inherit" a variable from the detail component.

Index.html.twig

Your Template can contain whatever you want. For this example, lets just put a {{myVariable}} in there.

Main.js

Include the component folder in the main.js as you do with other components.

Where you usually do it like this:

import './module/ec-crowdfunding-confirmation';
import './module/ec-crowdfunding-confirmation/page/index';
import './module/ec-crowdfunding-confirmation/page/detail';

Just add a

import './module/ec-crowdfunding-confirmation/page/detail/subcomponent-folder';

Detail.html.twig

In your Details twig file, include your component like this:

<my-component-name :myVariable="exampleVariable"/>

With :myVariable we "fill" the myVariable in our sub-component with the value we pass in within ="". In this case exampleVariable is a data attribute of our detail component.

Emit events

If you wanna call a function from the parent component - again, in our example this would be detail - within the child component, you have to emit events. Do this in your child components js file like this (in a method):

this.$emit('myEvent');

Then, edit your inclusion tag in the detail twig file like this:

<my-component-name :myVariable="exampleVariable" v-on:myEvent="function"/>

This tells the detail component to fire the function method everytime the child component emits the Event myEvent.