vue.js - 数据值仅在重新加载时加载,同时使用 VueJs v-bind
问题描述
使用 Vue 组件文件,我从 JSON API 获取一条记录并在模板中显示该记录数据,但它仅适用于重新加载页面。我正在使用 axios 和 v-bind 来获取和显示模板中的数据。
我尝试在脚本部分设置 cache: false 但我不确定这是否是我需要做的或如何做。
我需要放置或禁用某种类型的缓存设置吗?
<div id="PatientList" class="container">
<div>
<h3 class="heading" style="text-align:left">ID {{$route.params.id}}</h3>
<input id="lens" v-model= "search" placeholder ="Search here">
<br><br>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Mobile</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr v-bind:key="patient">
<td>{{ patient.id }}</td>
<td>{{ patient.first_name + " " + patient.last_name }}</td>
<td>{{ patient.mobile }}</td>
<td>{{ patient.email }}</td>
<td>></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
name: 'PatientList',
data () {
return {
patient: '',
}
},
mounted () {
axios
.get('http://localhost:8000/Patients/'+ this.$route.params.id +'/?format=json')
.then(response => (this.patient = response.data))
.catch(error => console.log(error))
},
}
</script>
<style>
#app {
text-align: center;
margin-top: 50px;
}
.heading {
margin-bottom: 30px;
}
#lens {
position: relative;
left: -468px;
}
</style>```
解决方案
当你在路由之间移动时,Vue 会尽可能地重用相同的组件。该mounted
钩子仅在组件第一次渲染时调用,因此如果组件没有更改,则不会再次调用它。
您需要注意路由参数何时更改:
watch: {
'$route.params.id' () {
// reload the data here
}
}
文档中描述了与您的场景几乎相同的场景:https ://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation 。在这种情况下,它使用watch
整体$route
而不是专门针对$route.params.id
,但最终结果大致相同。
更好的办法是id
使用路由器的设置将作为道具传递给组件,props: true
以消除对 的直接依赖$route
,但即便如此,您也需要注意道具值何时发生变化。有关更多信息,请参阅https://router.vuejs.org/guide/essentials/passing-props.html。
推荐阅读
- java - Gson 无法解析位于 json 对象中的 json 数组字符串作为 JsonArray
- python - ValueError:传递值的长度为 7,索引意味着 0
- ios - 我猜 NotificationCenter 发生 EXC_BAD_ACCESS 错误?
- r - 聚合一些列,同时保持其他列不变
- c++ - 给定一个整数 M,满足 (int)C < M 的最大浮点数 C 是多少?
- mysql - SQL JOIN 问答与 NULL 缺少答案
- c++ - Visual Studio 2017 上的 gtest/Google 测试 C++ 构建错误
- excel - 用于将家谱层次结构数据范围转换为列表数据的简单宏
- google-chrome-extension - 用于平衡内容脚本和后台脚本之间处理的模式
- python - 在 macos 中使用 pyinstaller 进行转换时包含“shape_predictor_68_face_landmarks.dat”的错误