如何更改nativescript-vue中列表项的颜色/ backgroundColor?

时间:2019-07-30 23:32:44

标签: nativescript nativescript-vue

我想在用户点击项目时更新所选的项目样式。 nextIndex / event.index已更新,但样式不适用。感谢您的帮助。

https://play.nativescript.org/?template=play-vue&id=ihH3iO

export default {
  name: "CustomListView",
  props: ["page", "title", "items", "selectedIndex"],
  data() {
    return {
      nextIndex: this.selectedIndex ? this.selectedIndex : undefined
    };
  },
  methods: {
    onItemTap(event) {
      this.nextIndex = event.index;
    }
  }
};
.selected {
  color: white;
  background-color: black;
}
<ListView for="(item, index) in items" @itemTap="onItemTap">
    <v-template>
    <Label :class="['list-item-label', { selected: index == nextIndex }]" :text="item" />
    </v-template>
</ListView>

1 个答案:

答案 0 :(得分:2)

有关此issue的更多信息。

  

这是预期的行为,因为滚动(视图回收)时,ListView的项目模板是由列表视图呈现和更新的,如果您需要确保在更改属性时列表视图已更新,请对其进行刷新。 / p>

所以解决方案是

<template>
    <Page class="page">
        <ActionBar title="Home" class="action-bar" />
        <ListView v-for="(item, index) in items" @itemTap="onItemTap" ref="listView">
            <v-template>
                <Label :class="[{selected: index === nextIndex}, 'list-item-label']"
                    :text="item" />
            </v-template>
        </ListView>
    </Page>
</template>

<script>
    export default {
        name: "CustomListView",
        data() {
            let selectedIndex = 2;
            return {
                items: ["Bulbasaur", "Parasect", "Venonat", "Venomoth"],
                nextIndex: selectedIndex
            };
        },
        methods: {
            onItemTap(event) {
                this.nextIndex = event.index;
                this.$refs.listView.nativeView.refresh();
            }
        }
    };
</script>

您需要刷新listView的代码为this.$refs.listView.nativeView.refresh();

不要忘记在ref上添加<ListView>