在VUE js中获取数组中数据的索引 [英] Getting index of a data in an array in VUE js

查看:2046
本文介绍了在VUE js中获取数组中数据的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在调用特定方法时更改任务的状态.但是问题是我无法获取数组特定项的索引来更改其状态. 这是我的HTML:

I want to change the status of Tasks when a particular method is called. But The problem is I cannot get the index of the particular item of the array to change its status. This is my HTML:

<div class="main" id="my-vue-app">
    <ul>
        <li v-for="task in completeTask">
            {{ task.description }} <button @click="markIncomplete">Mark as Incomplete</button>
        </li>

    </ul>
    <ul>
        <li v-for="task in incompleteTask">
            {{ task.description }} <button @click="markComplete">Mark as Complete</button>

        </li>
    </ul>
</div>

这是我的Vue:

<script>
    new Vue(
        {
            el: '#my-vue-app',
            data:
            {
                tasks: [
                {description:'go to market', status: true},
                {description:'buy book', status: true}, 
                {description:'eat biriani', status: true}, 
                {description:'walk half kilo', status: false}, 
                {description:'eat icecream', status: false}, 
                {description:'return to home', status: false}
                ]
            },
            computed: 
            {
                incompleteTask()
                {
                    return this.tasks.filter(task => ! task.status);
                },
                completeTask()
                {
                    return this.tasks.filter(task => task.status);
                }
            },
            methods: 
            {
                markComplete()
                {
                    return this.task.status = true;

                },
                markIncomplete()
                {
                    return this.task.status = false;
                }
            }
        }
    )
</script>

我需要使用markComplete()markIncomplete(),但是问题是我找不到获取当前元素索引以更改其状态的方法.

I need make use of markComplete() and markIncomplete() but the problem is I couldn't find the way to get the index of current element to change its status.

推荐答案

您可以通过

You could get the index by declaring a second argument at the v-for:

<li v-for="(task, index) in incompleteTask">
    {{ task.description }} <button @click="markComplete(index)">Mark as Complete</button>
</li>

    methods: 
    {
        markComplete(index)
        {
            return this.tasks[index].status = true;

        },


但是,也许更简单的替代方法是简单地传递task作为参数:


But a, maybe simpler, alternative is to simply pass the task as argument:

<li v-for="task in incompleteTask">
    {{ task.description }} <button @click="markComplete(task)">Mark as Complete</button>
</li>

    methods: 
    {
        markComplete(task)
        {
            return task.status = true;

        },

这篇关于在VUE js中获取数组中数据的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆