gpt4 book ai didi

javascript - Vue.js:在不同时使用 v-for 和 v-if 的情况下过渡元素的最佳方式?

转载 作者:行者123 更新时间:2023-12-03 06:45:58 27 4
gpt4 key购买 nike

我正在使用 v-for创建多个 <p>元素。 v-for用 Vue 包装 <transition>组件,因为我想要每个 <p>v-if 中设置动画条件满足。这是下面的代码:

<transition name="fade">
<p
v-for="(quote, idx) in game.quotes" <-- game.quotes comes from VUEX
:key="`game-quote-${idx}`"
class="quote-box__current_quote"
v-if="game.currentQuoteIdx === idx"
>"{{ quote.content }}"</p>
</transition>

但是,由于 vue/no-use-v-if-with-v-for,我收到 ESLINT 错误规则。

在研究了这条规则后,我被指向了以下 Vue 风格指南:https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential .该指南建议避免使用 v-forv-if在同一个元素上。我想使用 <transition> 为输入/输出的每个元素设置动画包装器组件(一次只能看到一个 <p> 标签)。有没有更理想的方法可以在不使用 v-if 的情况下实现我正在做的事情?和 v-for在同一个元素上?

其他问题:我在引用 game.quotes 时遇到以下错误在 v-for="(quote, idx) in game.quotes" :

The 'undefined' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'.

game.quotes来自 Vuex,数组不需要过滤。为什么 ESLINT 建议我创建计算属性并返回过滤后的数组?

FILE ON GITHUB - 第 10 行

最佳答案

以这个例子为例,它与你的非常相似:不要显示不必要的 li。将 v-forv-if 结合使用非常好,即使不是最佳实践。但是,有一种更简单的方法。

<h2>Items:</h2>
<ol id="list">
<li v-for="item in items" v-if="visible.includes(item)" :id="'item-'+item">
{{ item }}
</li>
</ol>

https://jsfiddle.net/oLjuy5bv/1/

正如其他两个答案所述,我们可以做的是创建一个计算方法并计算 v-for 的列表并删除 v-if .

<h2>Items:</h2>
<ol id="list">
<li v-for="item in visible_items" :id="'item-'+item">
{{ item }}
</li>
</ol>

computed: {
visible_items () {
return this.items.filter(item => this.visible.includes(item))
}
},

https://jsfiddle.net/17Ln5mw8/

我想你在那之后是这样的,它使用了一个方法,因为 idx 和可能的 game 上下文(我不知道逻辑特别是):

<transition name="fade">
<p
v-for="(quote, idx) in gameQuotesByIdx(idx)"
:key="`game-quote-${idx}`"
class="quote-box__current_quote"
>"{{ quote.content }}"</p>
</transition>

methods: {
gameQuotesByIdx(idx) {
return ...
}
},

我认为您可能遇到的问题是 react 性,这意味着组件可能不会响应数组状态的变化(上面的计算结果为我解决)。为此,您可能需要考虑重构。

关于javascript - Vue.js:在不同时使用 v-for 和 v-if 的情况下过渡元素的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59850633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com