【问题标题】:Append dynamic vue component after specific element在特定元素之后附加动态 vue 组件
【发布时间】:2017-05-16 15:29:24
【问题描述】:

我想根据其他元素的点击在随机位置添加组件(实际上不是随机的,基于某些逻辑)。

在 jQuery 中,我们可以通过$('#someId').append('element')$('#someId').find('.someClass').after('element') 实现这一点

我想要实现的(jquery 版本):jsfiddle

如何在 Vue 中做到这一点?

注意:v-for 无法做到这一点,因为所有元素不会按顺序出现或出现在同一个位置。此外,组件不应出现在初始化时,因为这是动态的。

【问题讨论】:

    标签: javascript jquery vue.js vue-component


    【解决方案1】:

    如果这是关于安排哪个组件将在另一个之后出现。假设我将所有这些组件放在一个数组中,您可以按照您的逻辑重新排列数组中的这些组件,并且您可以使用特殊属性:is 来呈现这些组件。

    在示例中,我有一组组件,我使用 v-for 一个接一个地渲染它们:

    见小提琴here

    HTML:

    <div id="app">
      <h1>
      Following are the components
      </h1>
      <div v-for="comp in compArray" :is="comp"></div>
      <br>
      <button @click="resuffle">
         Resuffle
      </button>
    </div>
    
    <template id="comp1">
      <div>
        <span>This is component 1</span>
      </div>
    </template>
    
    <template id="comp2">
      <div>
        <span>This is component 2</span>
      </div>
    </template>
    
    <template id="comp3">
      <div>
        <span>This is component 3</span>
      </div>
    </template>
    

    JS:

    Vue.component('comp1', {
      template: '#comp1', 
    })
    
    Vue.component('comp2', {
      template: '#comp2', 
    })
    Vue.component('comp3', {
      template: '#comp3', 
    })
    
    new Vue({
        el: '#app',
      data: {
        compArray: ['comp1', 'comp2', 'comp3']
      },
      methods: {
        resuffle: function() {
           this.compArray.push(this.compArray[1])
           this.compArray.splice(1,1)
        }
      },
    })
    

    【讨论】:

    【解决方案2】:

    当您遍历数组/列表以将元素与组件映射时,您能否提供一个父组件的示例? (只是为了了解您的用例)

    您可以使用v-for,但在您想要显示它们的位置(如果您想要显示组件的位置不是随机选择的)的某些计算属性生成的多个数组上。

    【讨论】:

    • 您可以从这里获得我想要实现的详细信息:stackoverflow.com/questions/41415523/… 无论如何,这不会是一系列项目。我想在不同的地方(点击面板的行之后)显示单个组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多