在Vue中处理链表

问题描述 投票:0回答:3

一个简单的数组可以像这样在 Vue 中渲染:

<ul>
    <li v-for="item in ['Item 1', 'Item 2', 'Item 3']"
        v-text="item" />
</ul>

是否有一种简单的方法可以使用如下所示的“链表”实现相同的结果,而不必嵌套元素或影响性能(例如,通过将列表转换为数组)?

{
    title: 'Item 1',
    next: {
        title: 'Item 2',
        next: {
            title: 'Item 3',
            next: null
        }
    }
}
vue.js vue-component
3个回答
0
投票

已编辑

通过使用

Object.keys()
Object.values()
迭代到对象中以创建要显示的新数组,将数据转换为可迭代对象(在本例中为数组)。


0
投票

正如 @destoryer 建议的那样,您可以创建一个

computed
属性,该属性将调用另一个函数来将链接列表转换为数组。

computed: {
  lists() {
    // assuming that linkedLists is in your data property

    // declared under `methods` in this example
    return this.flattenLists(this.linkedLists); 
  }
},
methods: {
  flattenLists({ title, next }) {
    return next ? [title].concat(this.flattenLists(next)) : [title];
  }
}

flattenLists
是一个递归函数,其中如果
next
是一个对象,它将以
next
作为参数调用自身,并将结果连接到当前数组。

在这个例子中,它位于

methods
下,但最好把它放在 作为助手/实用程序,特别是如果您想重用它 在其他组件中。

然后您可以在您的

v-for
中使用它。

<ul v-for="(item, index) in lists" :key="index">
  <li>{{ item }}</li>
</ul>

0
投票

我知道这是一个老问题,但你可以使用生成器函数来打印链接列表。

<script setup>
import { reactive } from 'vue'
const linkedList = reactive({
    title: 'Item 0',
    next: {
        title: 'Item 1',
        next: {
            title: 'Item 2',
            next: null
        }
    }
})

function* printLL(ll) {
  let temp = ll;

  while(temp !== null) {
    yield temp;
    temp = temp.next;
  }
}

</script>

现在您可以通过将链表作为参数传递来调用

printLL
并像往常一样在
v-for
中使用它,而无需任何额外的数组创建或计算值

<template>
  <div v-for="it in printLL(linkedList)">
    {{ it.title }}
  </div>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.