首页 > 解决方案 > 数据值仅在重新加载时加载,同时使用 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.jscaching

解决方案


当你在路由之间移动时,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


推荐阅读