【问题标题】:Access a single element from list of child elements of a reference in nuxt.js从 nuxt.js 中引用的子元素列表中访问单个元素
【发布时间】:2020-10-30 02:50:53
【问题描述】:

我对 nuxt 或 vue 不太熟悉,但我一直在从文档和示例中学习。
我尝试搜索了很多文章,但找不到一个简单的方法来做到这一点

我的组件是

<template>
    <div ref="parent">
        <div v-for="post in posts" v-bind:key="post.id">{{ post.title }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            posts: [
                {id: 1, title: 'title 1'},
                {id: 5, title: 'title 2'},
                {id: 7, title: 'title 3'}
            ]
        };
    },
    methods: {
        doSomething(){
            // I have to use the index of div but I want to use post.id
            const div = this.$refs.parent.children[0];
        }
    }
};
</script>

现在我想在post.id 的帮助下访问我的参考 div 的子元素 目前我正在使用索引访问子元素。

会有很多子元素,所以我不想添加对所有子元素的引用。

示例中的组件是一个子组件,我在父组件中访问它的方法并从那里传递post.id 作为doSomething(post.id) 方法中的参数

有人可以指导我吗?
提前致谢

【问题讨论】:

  • 可以分享下票的原因吗?

标签: javascript vue.js reference nuxt.js


【解决方案1】:

将 ID 传递给方法,然后使用它从 data() 中声明的数组中检索要更改的元素。

<template>
    <div ref="parent">
        <div v-for="post in posts" v-bind:key="post.id">
           {{ post.title }}
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            posts: [
                {id: 1, title: 'title 1'},
                {id: 5, title: 'title 2'},
                {id: 7, title: 'title 3'}
            ]
        };
    },
    methods: {
        doSomething(id){
           this.posts.map(x => {
               if(x.id === id){
                  //edit X here, where x is the post
                  console.log(x,'here I am');
               }
            return x
          });
        }
    }
};
</script>

希望这会有所帮助!

【讨论】:

  • 但是在子 div 或任何其他事件上不会有 @click 事件
  • 在我的问题中,我使用childref="parent" divs 角度引用迭代的div
  • 我错过了你的问题的一部分。我更新了我的答案,你可以将 id 传递给函数,然后用它来修改你的数组。
  • 抱歉,我并不想获取post,而是想访问ref="parent" 的子div(DOM 元素)。
  • 你想对 div 做什么?在这个简单的组件中使用 this.$refs.parent.children[0]; 访问它似乎很可能是对 vue 功能的滥用。
猜你喜欢
  • 2021-07-20
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多