4. 使用计算属性或方法代替
为避免上述问题, 我们应该在遍历模板中的数据之前对其进行过滤. 有两种非常相似的方法:
使用计算属性
使用过滤方法
让我们快速地介绍一下这两种方法.
首先, 我们只需要设置一个计算属性, 为了获得与之前的 v-if 相同的功能, 代码应如下所示.
- <ul>
- <li v-for='products in productsUnderFifty' :key='product._id'>
- {{ product.name }}
- </li>
- </ul>
- // ...
- <script>
- export default {
- data () {
- return {
- products: []
- }
- },
- computed: {
- productsUnderFifty: function () {
- return this.products.filter(product => product.price <50)
- }
- }
- }
- </script>
下面的代码几乎相同, 但是使用方法改变了我们访问模板中的值的方式, 如果我们希望能够将变量传递给筛选器, 那么方法是最好的选择.
<ul> <li v-for='products in productsUnderPrice(50)' :key='product._id'> {{ product.name }} </li> </ul> // ... <script> export default { data () { return { products: [] } }, methods: { productsUnderPrice (price) { return this.products.filter(product => product.price <price) } } } </script>
5. 在循环中访问项目的索引
除了遍历数组和访问每个元素之外, 我们还可以跟踪每个项的索引.
为此, 我们必须在项目后添加一个索引值, 它非常简单, 可用于分页, 显示列表索引, 显示排名等.
<ul> <li v-for='(products, index) in products' :key='product._id'> Product #{{ index }}: {{ product.name }} </li> </ul>
6. 遍历一个对象
到目前为止, 我们只真正看过使用 v-for 遍历数组, 但是我们可以轻松地遍历对象的键值对.
与访问元素的索引类似, 我们必须向循环中添加另一个值. 如果我们用一个参数遍历一个对象, 我们将遍历所有的项.
如果我们添加另一个参数, 我们将获得 items 和 key, 如果添加第三个, 我们还可以访问 v-for 循环的索引.
假设我们要遍历产品中的每个媒体资源.
<ul> <li v-for='(products, index) in products' :key='product._id'> <span v-for='(item, key, index) in product' :key='key'> {{ item }} </span> </li> </ul>
总结
希望这篇简短的文章能教您一些有关使用 vue 的 v-for 指令的最佳做法.
你还有什么其他建议吗?
近期推荐:
来源: http://www.tuicool.com/articles/mY3Irar