Vue.js - 如何使用事件克隆元素?

时间:2017-12-02 15:07:25

标签: javascript javascript-events vue.js vue-component

我有一个Vue.js插件,用户可以将这些元素作为插槽传输。我必须克隆其中一些(在特定情况下)。当然,用户可以向这些元素添加事件。例如:

<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>

如何使用所有Vue / JS事件克隆此插槽元素?最后渲染了HTML,例如:

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

    <!-- These are the original user 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>

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

1 个答案:

答案 0 :(得分:0)

您可以使用的是为上下文的第一部分和最后部分使用单独的插槽。

可以使用如下:

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>