如何将参数传递给Vue组件以启动组件实例

时间:2020-04-09 20:02:05

标签: javascript vue.js

我对Vue很陌生。我正在尝试学习如何创建和重用Vue组件。传递给组件的初始数据不会在click事件上更新。 这是我的代码(完整版本位于https://jsfiddle.net/gpawel/486ysvxj/33/) 我做错了什么? 谢谢。

<div id="components-demo">
  <button-counter count='3'></button-counter>
  <br><br>
  <button-counter count='4'></button-counter>
</div>

Vue.component('button-counter', {
    props: ['count'],
    methods: {
    add: function() {
        return {count: count++}
    }
  },
  template: '<button v-on:click="add()">You clicked me {{count}}  times.</button>'
})

new Vue({ 
    el: '#components-demo'
})

3 个答案:

答案 0 :(得分:1)

这是工作中的小提琴:https://jsfiddle.net/68p1u9ks/

Vue.component('button-counter', {
    props: ['initialCount'],
    data: function () {
        return {
          count: 0,
        }
    },
    methods: {
        add: function() {
            this.count++
        },
    },
    created() {
          this.count = this.initialCount
    },
    template: '<button v-on:click="add()">You clicked me {{count}}  times.</button>'
})

我认为您需要维护button-counter组件内部的状态。还将count道具重命名为initial-count

<div id="components-demo">
  <button-counter :initial-count='3'></button-counter>
  <br><br>
  <button-counter :initial-count='4'></button-counter>
</div>

答案 1 :(得分:1)

查看更新后的fiddle。您将直接更改count属性,首先将其另存为数据,然后更改internalCount。另外,使用:将prop强制转换为Number而不是字符串。

props: ['count'],
  data() {
  return {
    internalCount: this.count
  }
},
methods: {
  add: function() {
    return {
      count: this.internalCount++
    }
  }
},

答案 2 :(得分:1)

您不能在子组件中更改道具。 您应该使用$emit来更改道具:

父组件:

<template>
<div>
  <child :count="count" @add="add" />
</div>
</template>
<script>
export default {
  data: () => ({
    count: 1
  }),
  methods: {
   add() {
     this.count = this.count + 1;
   }  
  }
}
</script>

和子组件:

<template>
  <button v-on:click="add()">You clicked me {{inComponentCount}}  times.</button>
</template>
<script>
export default {
  props: [count],
  computed: {
    inComponentCount() {
      return this.count;
    }
  },
  methods: {
   add() {
     this.$emit('add')
   }  
  }
}
</script>