【问题标题】:How to refer to specific dynamically added component from number of dynamically added components in Vue, version 2.9如何在Vue 2.9版中从动态添加的组件数量中引用特定的动态添加的组件
【发布时间】:2022-01-11 08:54:26
【问题描述】:

个人 id 或我可以调用以在组件上运行函数的任何其他元素是什么或在哪里。

示例:我使用添加按钮动态创建彩色方块。每个方块都有关闭按钮。

然后我想删除一个正方形,比如说蓝色的那个(模板的第三个孩子)。

v-bind:id='var' 不起作用,因为所有方块都具有相同的 id。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您可以使用 ref,您可以在每个添加的组件中定义 ref。 ref 是数组。您可以通过引用的索引来引用组件。 例如;<div v-for="(item) in arr" :key="item.id"> <span ref="testRef"> item.name </span> </div>,你可以使用 'this.$refs.testRef[index]' 找到你想要的组件。

    【讨论】:

      【解决方案2】:

      有多种选择。例如,在您的 v-for 循环中,您可以通过以下方式获取索引:(official docs)

      <div v-for="(item, index) in myList" :key="index">
          {{ item.name }}
      </div>
      

      然后,您可以使用 ref 中的索引来访问脚本的元素。

      另一种选择是使用特殊关键字$event 将事件实例传递给onclick 侦听器,并使用它来获取元素:

      <div ... @click="myFunction($event)">
          {{ item.name }}
      </div>
      

      然后在你的脚本中

      myFunction(ev) {
        // do something with the element that was clicked on
        console.log(ev.target)
      }
      

      然而,一种更“vue”的方式是不要弄乱元素,而只是操纵底层数据,让 vue 担心用页面上的元素表示数据。例如,您可以让您的方块由一个对象列表表示,包含它们自己的数据拥有状态(打开或关闭)。所以在你的脚本中你有:

      data() {
        return {
          squares: [
            { color: "ff0000", opened: true },
            ...
          ]
        }
      },
      

      在您的模板中类似于

      <div
          v-for="square in squares"
          v-show="suare.opened"
          @click="square.opened = false" 
      > ... 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        • 2018-07-02
        • 1970-01-01
        • 2021-02-08
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多