【发布时间】:2019-11-23 03:41:29
【问题描述】:
我遇到了一个问题,希望 Javascript Jedi 能帮助我指明正确的方向。
问题范围:
我将 Laravel 集合传递给我的 Vue 组件。在组件内部,我正在遍历集合并通过 axios 提交表单。表单提交,数据在数据库中更新,但是__我不清楚如何在不刷新页面的情况下显示更新的值。__
预期结果:
表单提交后,更新后的数据会反映在Vue模板内的{{ collection.value }}中
出了什么问题:
数据库中的数据正在更新,但{{ collection.value }} 保持不变,直到重新加载页面。
Web.php:
Route::post('/updateQty', 'MyController@update');
我的控制器:
public function update(Request $request)
{
$product = Product::where('id', $request->productId)
->update([ 'qty' => $request->qty ]);
return response()->json($product);
}
public function index()
{
$collection = DB::table('products')->get();
return view('my-blade', [
'collections' => $collection,
]);
}
$collection 存储在数据库中的结构:
'qty' => decimal(8,2),
'class' => varchar(255),
'description' => varchar(255),
'value' => decimal(8,2),
'productId' => int(11)
我的刀片:
<my-component :collections="{{ $collections }}"></my-component>
MyComponent.vue:
<template>
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table table-sm">
<div v-if="collections.length">
<tr v-for="collection in collections" v-bind:key="collection.id">
<td>
<form @submit="updateQty">
<input type="hidden" id="productId" :value="collection.productId" name="productId">
<select class="form-control" name="qty" id="qty" @change="updateQty">
<option :value="collection.qty">{{ collection.qty }}</option>
<option v-for="(x, index) in 200" v-bind:key="index" :value="index">{{ index }}</option>
</select>
</form>
</td>
<td>{{ collection.value }}</td>
</tr>
</div>
</table>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['collections'],
data() {
return {
qty: '',
}
}
mounted() {
console.log('MyComponent.vue mounted successfully');
},
methods: {
updateQty(e) {
e.preventDefault();
let currentObj = this;
let url = '/updateQty';
axios.post(url, {
qty: qty.value,
})
.then(function (response) {
currentObj.value = (response.data);
let collections = response.data;
})
},
}
}
</script>
App.js
Vue.component('my-component', require('./components/MyComponent.vue'));
我确信这很简单,但对于我的一生,我无法理解它。非常感谢您!
【问题讨论】:
标签: javascript laravel vue.js