I have a Vue component that load the data of books from the back-end and then put then into cards.
I wanted to allow the user to change the sorting of the books from default to by rating or the newest etc, so I declared a variable name sorting
and set to default and add a drop-drown menu to change the variable sorting from default, and put the variable in the URL that get the data from the back end like in get_books
method:
data(){
return {
audio_books:[],
page:1,
last_page:false,
sorting:"default",
}
},
methods: {
get_books() {
axios.get('load_all_audio_books/' this.sorting '?page=' this.page).then(response=> {
$.each(response.data.data, (key, v) => {
this.audio_books.push(v);
if (response.data.current_page==response.data.last_page){
this.last_page=true;
}
});
})
this.page ;
},
the back end :- web.php
Route::get('/load_all_audio_books/{sort}',[\App\Http\Controllers\load_book::class,'get_all_audiobooks']);
the back-end function:-
public function get_all_audiobooks($sort)
{
if($sort=="default")
{
$books=DB::table('audio_books')->paginate(10);
return $books;
}
elseif ($sort=="rate")
{
$books=DB::table('audio_books')->orderBy('rating','desc')->paginate(10);
return $books;
}
elseif ($sort=="newest")
{
$books=DB::table('audio_books')->orderBy('created_at','desc')->paginate(10);
return $books;
}
elseif ($sort=="oldest")
{
$books=DB::table('audio_books')->orderBy('rating')->paginate(10);
return $books;
}
now what I want is to re-render the component whenever the variable sorting change.
CodePudding user response:
You will need to create a computed method which uses the sorting
data property.
Something like so:
data() {
return {
// addition to what you already have
sortOptions: [ 'prop1', 'prop2' ]
}
},
computed: {
sortedBooks() {
return this.audio_books.sort((a, b) => a[this.sorting] - b[this.sorting])
// assuming it will always been ascending here
}
}
Now you can set the sort property to whatever property you want to sort by.
Every time that value changes, the list will be re-rendered.
CodePudding user response:
A watcher seems like it would work: https://v3.vuejs.org/guide/computed.html#watchers