【发布时间】:2020-02-04 19:46:25
【问题描述】:
我正在创建一个显示产品的 Web 应用程序(所有产品信息都来自数据库),每个产品都有一个 More Details >> 按钮,单击时会打开一个包含该特定产品信息的模式窗口。 js 文件包含被多次调用的 allRecords() 函数,这使得检查中的网络选项卡变得疯狂。我希望它只被调用一次。我看过这个:How to trigger a vue method only once, not every time,我不确定如何将它应用到我的代码中。
下面是我的代码:
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
}
}
})
【问题讨论】:
-
为什么要在模板中执行方法?也许在创建的循环中运行它
-
您可以在组件的
mounted挂钩中执行ajax 请求,并让回调设置allRecords属性。然后用{{allRecords}}代替{{allRecords()}}。 -
在vue的文档vuejs.org/v2/api/#created
-
@ConstantinGroß 谢谢!所以我在js文件中添加了
mounted: function() { this.allRecords() // Calls the method before page loads },,并删除了(),正如你所说,我在这里做错了吗?我得到:function () { [native code] } -
你想在
<h1>标签中显示什么?
标签: javascript vue.js axios bootstrap-vue