How can I change color / backgroundColor of list item in nativescript-vue?

 ̄綄美尐妖づ 提交于 2020-08-11 02:13:55

问题


I want to update selected item style when user taps on items. nextIndex/event.index is updated but style doesn't apply. Thanks for your help.

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:


More info about this issue.

This is expected behavior because the ListView's item template is rendered and updated by the list view when scrolling (view recycling) if you need to make sure the list view is updated when you change your property, call refresh on it.

So the solution is


<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>

You need refresh your listView the code for that is this.$refs.listView.nativeView.refresh();

Don't forget to add the ref on the <ListView>



来源:https://stackoverflow.com/questions/57281319/how-can-i-change-color-backgroundcolor-of-list-item-in-nativescript-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!