v-for不重新渲染数组vue js

时间:2020-05-21 13:51:15

标签: javascript vue.js v-for vue-reactivity

我有一个SPA,其中我使用v-for显示口袋妖怪的数组,并可以按类型或世代筛选这些列表。我有一个按钮可以清除过滤器(将类型设置为”,将生成设置为1代),但是在清除过滤器后,v-for循环不会重新渲染数组。我已经记录了返回宠物小精灵数组以确认其正常工作的函数,但是Vue JS不会呈现结果。我不确定如何进行。

<div class="pokemon"
            v-for="pokemon in filteredPokemon"
            :key="pokemon.id">
                <h2>{{ pokemon.name }}</h2>
</div>

<script>
import Pokemon from '../pokeData'

export default{
props: ['searchFilters'],
data(){
        return{
            allPokemon: [],
        }
    },
created(){
            this.allPokemon = Pokemon.getPokemon('gen1');
    },
computed: {
        filteredPokemon: function(){ 
            if(this.searchFilters.type){
                if(this.searchFilters.type === ''){
                    return this.allPokemon
                }
                return this.allPokemon.filter(pokemon => {
                    if(pokemon.types.length === 2){
                        if(pokemon.types[0].type.name == this.searchFilters.type || pokemon.types[1].type.name == this.searchFilters.type){
                            return true
                        }
                    }
                    else if(pokemon.types[0].type.name == this.searchFilters.type){
                            return true
                        }
                })
            }
            return this.allPokemon
        }
    },
watch:{
        'searchFilters.generation': function(generation){
            this.allPokemon = Pokemon.getPokemon(generation)
        }
    }
}
}
</script>

1 个答案:

答案 0 :(得分:1)

farincz是正确的,您正在通过对getPokemon和Vue的函数调用来更改allPokemon的属性。JS找不到更改(documentation),因此这是一个警告,您需要在一种不同的方式,因为Vue不支持您想要的方式。

我将使用具有计算值的过滤器方法过滤所有神奇宝贝,并将过滤器值绑定到数据属性:

HTML:

<!--This would be your list-->
<div style="display: inline-flex;">
  <ol>
    <li>Sample List
      <ul>
        <li>1</li>        
        <li>2</li> 
        <li>3</li>
        <li>4</li>
      </ul>
    </li>
  <ol>
</div>
<!--And this would be your table-->
<div style="display: inline-flex;">
  <table>
    <tr>
      <th>Test</th>
      <th>Table</th>
    </tr>
    <tr>
      <td>This is a test table</th>
      <td>Sample Text</th>
    </tr>
    <tr>
      <td>Lorem Ipsum</th>
      <td>More Lorem Ipsum</th>
    </tr>
  </table>
</div>

JS文件:

<template>
  <div>
    <textarea v-model="text" name="filter" cols="30" rows="2"></textarea>
    <div class="pokemon" v-for="pokemon in filteredPokemon" :key="pokemon.id">
      <h2>{{ pokemon.name }}</h2>
    </div>
  </div>
</template>

这里是jsfiddle可以玩耍的地方。