首页 > 解决方案 > 是否可以从主 Vue 实例的方法中添加/删除组件的道具?

问题描述

在 Vue.js 上,我有一个prop名为loading的 v-button 组件。

零件:

Vue.component('v-button', {
    props: ['loading'],
    template: '<button class="btn btn-info"> <span v-if="loading != undefined">Loading...</span> <span v-else><slot></slot></span> </button>'
});

视图:

new Vue({
    el: '#app',
    components: ['v-button'],
    methods: {
        niceMethod: function(argument) {
        console.log(argument);
        // Considering that I will have a large amount of v-buttons:
        // Is it possible to do something here to add or remove the prop "loading" ONLY on the v-button I've clicked?
    }
  }
})

身体:

<div id="app" class="p-5">
  <p><v-button @click.native="niceMethod('testing!')">Test</v-button></p>
  <p><v-button @click.native="niceMethod('hello!')">Hello</v-button></p>
  <p><v-button @click.native="niceMethod('vue!')">Vuejs</v-button></p>
</div>

考虑到我会有大量的 v 按钮:是否可以在 Vue 实例上做一些事情来添加删除仅在我单击的 v 按钮上加载的道具?

我错过了 Vue.js 文档上的内容吗?

对不起,如果我的问题不清楚......如果是这样,请检查我所做的JSFiddle 。

标签: javascriptvue.jsvuejs2clickdom-events

解决方案


为什么不在loading组件内切换数据真/假?

Vue.component('v-button', {
  template: '<button class="btn btn-info" @click="clickMe"> <span v-if="loading">Loading...</span> <span v-else><slot></slot></span> </button>',
  data() {
    return {
      loading: false
    }
  },
  methods: {
    clickMe() {
      this.loading = !this.loading
    }
  }
});

new Vue({
  el: '#app',
  components: ['v-button'],
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <p><v-button>Test</v-button></p>
  <p><v-button>Hello</v-button></p>
  <p><v-button>Vuejs</v-button></p>
</div>


推荐阅读