是否可以在主Vue实例上的方法中添加/删除组件的道具?

时间:2018-06-08 21:05:11

标签: vue.js javascript-events vuejs2 click vue-component

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

组件:

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>'
});

Vue的:

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我做了。

1 个答案:

答案 0 :(得分:0)

为什么不在组件内切换数据loading true / false?

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>