Cloning elements with events in Vue.js: A step-by-step guide

Within my Vue.js plugin, I have implemented a feature where users can pass elements as slots. In certain scenarios, I need to duplicate some of these elements while ensuring that any attached events remain intact. For instance:

<component>
    <div class="slot-item" @click="myMethod(1)"></div>
    <div class="slot-item" @click="myMethod(2)"></div>
    <div class="slot-item" @click="myMethod(3)"></div>
</component>

Can you advise on how to clone these slot elements along with their associated Vue/JS events? Ultimately, the desired output should resemble the following rendered HTML:

<div class="my-component">
    <!-- This is the last cloned item -->
    <div class="slot-item cloned-slot-item" @click="myMethod(3)"></div>

    <!-- These are the original user-supplied elements -->
    <div class="slot-item" @click="myMethod(1)"></div>
    <div class="slot-item" @click="myMethod(2)"></div>
    <div class="slot-item" @click="myMethod(3)"></div>

    <!-- This is the first cloned item --> 
    <div class="slot-item cloned-slot-item" @click="myMethod(1)"></div>
</div>

Answer №1

Utilizing separate slots for the initial and final parts of the content can be quite advantageous.

Here is one way to implement this technique:

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

new Vue({
  el: '#demo',
  template: '#example-app',
  methods: {
    log(m, classTest) {
      console.log(m, classTest);
    },
  },
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>



<script type="text/x-template" id="example-component">
    <div>
        <slot name="last" className="clone"></slot>
        <slot name="first"></slot>
        <slot></slot>
        <slot name="last"></slot>
        <slot name="first" className="clone"></slot>
    </div>
</script>
<script type="text/x-template" id="example-app">
    <example-component>
        <template slot="first" slot-scope="props">
            <div @click="log('first: ', props.className)" :class="props.className">
                first
            </div>
        </template>
        <div @click="log('middle1')">
            middle1
        </div>
        <div @click="log('middle2')">
            middle2
        </div>
        <template slot="last" slot-scope="props">
            <div @click="log('last: ', props.className)" :class="props.className">
                last
            </div>
        </template>
    </example-component>
</script>
<div id="demo">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Text in d3.js vanishing while undergoing rotation

I have been struggling for hours with what seems like a simple problem and haven't made any progress. I'm hoping to receive some valuable advice from the brilliant minds on stackoverflow. You can view my demo at I attempted to use jsfiddle to s ...

*Running a NodeJS/VueJS application with Vagrant and VirtualBox: A step-by-step guide*

Here is the source code: https://github.com/tenzan/dmb-vagrant Attempting to set up a development environment with: Main Operating System: Windows 10 Vagrant - latest version VirtualBox - latest version NodeJS/VueJS Below is the Vagrantfile configuratio ...

Encountering an issue: Unhandled error - Unable to access property 'parentNode' of a null value

I'm attempting to add a new div next to another div using the ComponentID of the first div as a reference. I want to place the second div parallel to the first one, like this: <div> <div id="userActivityStatusMenu-1110">Neighbor 1< ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

What is the most effective way to load data prior to the controller being loaded

Is there a way to fetch data from a service before the view and controller are loaded? I need assistance with this. resolve: { getAlbum: function(albumService){ return albumService.getAlbums(); },getAtum: function(albu ...

Navigating through JavaScript list items

When I send an API request, the response I get looks something like this: //Sample Response [ { "id": 34, "user_id": 1, "first_name": "Awesome", "last_name": "Person", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Is there a way to navigate directly to a specific section without triggering scroll behavior? Are there any alternatives to scrollIntoView() that do not

I'm currently working on setting up a page redirection to a specific section, aiming to navigate to a particular anchor div without any scrolling behavior. However, I've encountered an issue with the #id method due to having a query string in the ...

Is it possible to utilize Class objects within Google Apps Script Libraries?

Recently, I've been working on a JavaScript class that looks like this: class MyObject { constructor(arg1, arg2, arg3) { this.field1 = arg1; this.field2 = arg2; this.field3 = arg3; } myMethod(param1, param2) { return param + par ...

Guide to integrating Google Maps JS API into a React application without relying on third-party libraries

I'm currently grappling with the concept of integrating external APIs in React and am interested in using Google Maps' API to showcase a map within a child component. My goal is to gain insight into how this can be done without relying on any ext ...

Issues arise with Vue.js's declarative rendering functionality after the bundling process with webpack

Here is a snippet from my index.html file: <!doctype html> <html><head> <body> <h1>ES</h1> <div id="app"> {{ message }} </div> <script src="dist/main.js" type="text/javascri ...

Has anybody successfully implemented the danfojs-node package on an Apple M1 chip?

I encountered an issue when trying to use danfojs-node on a Mac with an M1 chip - it kept crashing due to TensorFlow. I'm curious if anyone has managed to successfully integrate the npm package from this link (https://www.npmjs.com/package/danfojs-nod ...

Creating three-dimensional text in Three.js

My script is based on this documentation and this resource. Here is an excerpt of my code: <script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script> <script> var text = "my text", height = 20 ...

Refresh the inner content (Reverberate PHP) when the button is clicked

Currently, I am at the beginner's level of WordPress and PHP. Despite my efforts in researching on stackoverflow, my limited understanding has hindered me from finding a solution to my issue. On my website, I am utilizing WordPress as the CMS. Specif ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components. Here is the code snippet: <template> <div> <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map">&l ...

The checkbox filter in Angular 6 has the ability to replace the previously selected

I've been working on creating a filter system using checkboxes. Below is a snippet of the code I'm currently using: filter.pipe.ts import { Pipe, PipeTransform, Injectable } from '@angular/core'; @Pipe({ name: 'filter2' }) ...

Executing NodeJS commands and Linux commands via Crontab scheduling

I have an EC2 AWS instance where various commands and scripts work perfectly, but do not execute within a crontab. The Crontab contains: 15 03 * * * pythonscript1.py 45 03 * * * pythonscript2.py 00 05 * * * gsjson 1z5OlqsyU5N2ze1JYHJssfe1LpKNvsr4j8TDGnvyu ...

Struggling with smoothly transitioning an image into view using CSS and JavaScript

I'm currently experimenting with creating a cool effect on my website where an image fades in and moves up as the user scrolls it into view. I've included the code I have so far below, but unfortunately, I keep getting a 404 error when trying to ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

Having trouble retrieving the necessary redirect_uri in react-facebook-login

I am currently working on implementing Facebook OAuth in my express/NodeJS app using the authorization code flow. To fetch the authorization code, I am utilizing the react-facebook-login node module. While I can successfully obtain the authorization code i ...