我有一個 Vue 組件,它從后端加載書籍資料,然后放入卡片中。
我想讓用戶將書籍的排序從默認更改為按評級或最新等,因此我宣告了一個變數名稱sorting并設定為默認值并添加一個下拉選單以更改默認值的變數排序,然后將URL中從后端獲取資料的變數,如get_books方法:
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 ;
},
后端:- web.php
Route::get('/load_all_audio_books/{sort}',[\App\Http\Controllers\load_book::class,'get_all_audiobooks']);
后端功能:-
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;
}
現在我想要的是每當變數排序發生變化時重新渲染組件。
uj5u.com熱心網友回復:
如果你想在后端執行排序,你就完成了一半(我發現這page部分令人困惑,所以我暫時從下面的演示中洗掉了它)。
- 創建一個觸發 HTTP 呼叫的方法(按方法完成
get_books) - 創建一個監聽器來監聽 的值的變化
sorting。 - 使用觀察器再次觸發 HTTP 呼叫
<template>
<!-- Other stuff -->
<select v-model="sorting">
<option value="prop1">Prop 1</option>
<option value="prop2">Prop 2</option>
</select>
<!-- Other stuff -->
</template>
<script>
watch: {
sorting(newVal, oldVal) {
this.get_books(newVal)
}
},
mounted() {
this.get_books(this.sorting)
},
methods: {
get_books(sort) {
axios.get(`load_all_audio_books/${sort`).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;
}
});
})
},
}
</script>
觀察者是一種解決方案。你可以用多種不同的方式來做到這一點。
uj5u.com熱心網友回復:
我通過將這兩行添加到更改變數“排序”值的函式中解決了這個問題
change_sort(sort)
{
this.page=1;
this.sorting=sort;
//the first line empty the audio_books array
this.audio_books=[];
//the second line call the function that get the data from the
//back end with the new sorting value then repopulate the
//audio_books array with the new values
this.get_books();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/381428.html
標籤:javascript Vue.js Vue 组件
