如何在 Vue 中只执行一次方法?

我正在创建一个显示产品的 Web 应用程序(所有产品信息都来自数据库),每个产品都有一个More Details >>按钮,单击时会打开一个包含该特定产品信息的模式窗口。js 文件包含被多次调用的 allRecords() 函数,这使得检查中的网络选项卡变得疯狂。我希望它只被调用一次。我看过这个:如何只触发一次 vue 方法,而不是每次都触发,我不确定如何将它应用到我的代码中。


这是我的代码如下:


PHP文件


<div id="myapp">

  {{ allRecords() }}

  <div class="content">

    <div class="nested" v-for="product in products">

      ...

    </div>

    <b-modal id="productModal" v-if="chosenProduct" hide-footer="true" ok-title="Buy Now" size="lg" :title="chosenProduct.Name">

      <div class = "inner-container">

        ...

      </div>

    </b-modal>

  </div>

</div>

JS文件


var app = new Vue({

  'el': '#myapp',

  data: {

    products: "",

    chosenProduct: null

  },

  methods: {

    allRecords: function(){ \\ This function here is being called multiple times

      axios.get('ajaxfile.php')

        .then(function (response) {

          app.products = response.data;

        })

        .catch(function (error) {

          console.log(error);

        });

    },

    chooseProduct: function (product) {

      app.chosenProduct = product

    }

  }

})


慕运维8079593
浏览 1299回答 1
1回答

慕容3067478

根据我上面的评论:您可以在组件的挂载钩子中执行 ajax 请求。您的回调已设置该products属性。然后就不需要{{allRecords()}}从模板调用了,你可以简单地products在你的v-for循环中使用。这是该方法的演示。为了演示(和娱乐)目的,我将您的 php 替换为 icanhazdadjoke API。var app = new Vue({&nbsp; 'el': '#myapp',&nbsp; data: {&nbsp; &nbsp; products: "loading dad joke...",&nbsp; &nbsp; chosenProduct: null&nbsp; },&nbsp; methods: {&nbsp; &nbsp; chooseProduct: function(product) {&nbsp; &nbsp; &nbsp; app.chosenProduct = product;&nbsp; &nbsp; }&nbsp; },&nbsp; created: function() {&nbsp; &nbsp; axios.get('https://icanhazdadjoke.com/search?term=dogs', {&nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; Accept: 'application/json'&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; .then(function(response) {&nbsp; &nbsp; &nbsp; app.products = response.results;&nbsp; &nbsp; })&nbsp; &nbsp; .catch(function(error) {&nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; });&nbsp; }})<script src="https://unpkg.com/axios@0.2.1/dist/axios.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="myapp">&nbsp; <p v-for="product in products">&nbsp; &nbsp; {{product.joke}}&nbsp; </p></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript