将数据传递给许多组件之一

时间:2018-05-25 22:48:02

标签: javascript vue.js vuejs2 vue-component

我正在尝试在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
   }
}

1 个答案:

答案 0 :(得分:1)

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

以下是您想要的快速而简单的示例:

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>