gpt4 book ai didi

javascript - 将数据传递到多个组件之一

转载 作者:行者123 更新时间:2023-12-03 01:48:08 26 4
gpt4 key购买 nike

我正在尝试在 VueJS 中创建一个 DownloadButton 组件,该组件在单击时会产生动画,并在下载完成后停止动画。 DownloadButton 组件将在重复多次的表格中使用。我希望下载方法包含在父级中。问题在于,更改加载变量会导致所有组件受到影响,而不仅仅是被单击的组件。

父级:

<DownloadButton @click.native="download" :loading="loading"></DownloadButton>
<DownloadButton @click.native="download" :loading="loading"></DownloadButton>
<DownloadButton @click.native="download" :loading="loading"></DownloadButton>

methods: {
download() {
this.loading = true
// wait for the download procedure to finish...
this.loading = false
}
}

最佳答案

您应该监控每个按钮的加载状态,而不仅仅是全局加载。

这是我认为您想要的快速而简单的示例:

Vue.component("download-button", {
template: "#dbTemplate",
props: ['loading'],
computed: {
stateText() {
return this.loading ? 'Loading...' : 'Load';
}
}
});

new Vue({
el: "#app",
data: {
resources: [
{ date: new Date(), url: "some-url1" },
{ date: new Date(), url: "some-url2" },
{ date: new Date(), url: "some-url3" },
{ date: new Date(), url: "some-url4" }
],
resourceStates: {}
},
methods: {
downloadResource(resource) {
this.$set(this.resourceStates, resource.url, true);
new Promise((resolve, reject) => {
setTimeout(() => resolve(new Date()), 1000);
}).then((date) => {
resource.date = date;
this.$set(this.resourceStates, resource.url, false);
})
},
isLoading(resource) {
return !!this.resourceStates[resource.url];
}
}
});
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<div v-for="res in resources" :key="res.url" style="padding: 10px 0">
{{ res.date.toLocaleString() }}&nbsp;
<download-button @click.native="downloadResource(res)" :loading="isLoading(res)">
</download-button>
</div>
</div>

<script type="text/template-x" id="dbTemplate">
<button :disabled="loading">
{{ stateText }}
</button>
</script>

关于javascript - 将数据传递到多个组件之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com