【发布时间】:2021-06-14 21:29:18
【问题描述】:
在 Vue2 中,当我在选择中选择一列时,我想按列对我的测验数组进行排序。但是当我更改选择时 _.orderBy (lodash) 不会排序,它会调整 sortDirection。 orderBy 在 sortDirection 更改时执行。我没有错误。有谁知道我做错了什么?非常感谢您的提示!
vue 组件
<template>
<div class="py-6">
<div class="max-w-7xl mx-auto lg:px-8">
<div class="mt-5 flex lg:mt-0">
<span class="block w-1/5">
<input v-model="search" autocomplete="no"
class="ml-3 border border-gray-300 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm rounded-md"
placeholder="Zoek hier naar quizzen..."
type="text">
</span>
<span class="block">
<select v-model="sortProperty"
class="ml-6 block w-full py-2 px-4 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
name="sortBy">
<option value="name">Naam</option>
<option value="playdate">Speeldatum</option>
</select>
</span>
<span class="block">
<button
class="ml-9 inline-flex justify-center py-2 border border-transparent text-sm font-medium rounded-md text-gray-500 focus:outline-none"
type="button" @click="sortDirection === 'asc' ? sortDirection = 'desc' : sortDirection = 'asc'">
<svg v-if="sortDirection === 'asc'" class="h-5 w-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg">
<path d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12" stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"/>
</svg>
<svg v-if="sortDirection === 'desc'" class="h-5 w-5 mr-3" fill="none" stroke="currentColor"
viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4" stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"/>
</svg>
</button>
</span>
</div>
<div v-for="quiz in filteredQuizzes" v-if="filteredQuizzes.length > 0"
class="bg-white rounded-lg shadow-sm duration-500 px-2 sm:px-6 md:px-2 py-4 my-6">
<div class="grid grid-cols-12 gap-3">
<div class="col-span-12 sm:col-start-3 sm:col-end-13 px-3 sm:px-0">
<div class="mt-2">
<a class="sm:text-sm md:text-md lg:text-lg text-gray-700 font-bold">
{{ quiz.name }}
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import _ from 'lodash';
import axios from "axios";
export default {
data() {
return {
search: '',
sortProperty: 'name',
sortDirection: 'asc',
quizzes: [],
}
},
computed: {
filteredQuizzes() {
let quizzes = this.quizzes.filter(quiz => quiz.name.toLowerCase().includes(this.search.toLowerCase()))
return _.orderBy(quizzes, this.sortProperty, this.sortDirection)
}
},
created() {
this.fetchQuizzes();
},
methods: {
fetchQuizzes() {
axios.get('/quizzes').then(({data}) => (this.quizzes = data));
},
},
name: "Quizzes"
}
</script>
【问题讨论】:
-
我相信这应该可以正常工作。确保您在测验对象上有属性
playdate(如果它们的值相同,则选择时不会看到任何变化)。也尽量不要在与v-for相同的元素上使用v-if,并将:key与v-for 一起使用。
标签: javascript vuejs2 lodash laravel-8 columnsorting