【问题标题】:Data Value loads only on reloading, while using VueJs v-bind数据值仅在重新加载时加载,同时使用 VueJs v-bind
【发布时间】:2020-01-19 09:03:17
【问题描述】:

使用 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>```

【问题讨论】:

  • 在使用相同组件的路由之间导航时是否出现问题?所以只是 id 正在改变?
  • 当它第一次在路线上加载时,它工作正常,当更改路线时,只有 ID 发生变化,并且在重新加载完成之前不会更新值。

标签: vue.js caching


【解决方案1】:

当你在路由之间移动时,Vue 会尽可能地重用相同的组件。 mounted 钩子只在组件第一次渲染时被调用,所以如果组件没有改变就不会再次调用。

您需要注意路由参数何时发生变化:

watch: {
  '$route.params.id' () {
    // reload the data here
  }
}

文档中描述了与您的场景几乎相同的场景:https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation。在这种情况下,它在整个$route 上使用watch,而不是专门针对$route.params.id,但最终结果大致相同。

更好的办法是使用路由器的props: true 设置将id 作为prop 传递给组件,以消除对$route 的直接依赖,但即便如此,您也需要注意prop 值何时发生变化.请参阅https://router.vuejs.org/guide/essentials/passing-props.html 了解更多信息。

【讨论】:

  • 谢谢@skirtle!完美运行
猜你喜欢
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 2023-04-04
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多