【问题标题】:How to pass parameter to a Vue component to initiate components instance如何将参数传递给 Vue 组件以启动组件实例
【发布时间】:2020-07-22 13:19:10
【问题描述】:

我对 Vue 很陌生。我正在尝试学习如何创建和重用 Vue 组件。传递给组件的初始数据不会在单击事件上更新。 这是我的代码(完整版在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'
})

【问题讨论】:

  • @Daviti 你还在直接修改道具this.count += 1
  • 这能回答你的问题吗? Vue.js Changing props

标签: javascript vue.js


【解决方案1】:

查看更新后的fiddle。您正在直接改变 count 属性,首先将其保存为数据并改变 internalCount。另外,使用: 将道具转换为数字而不是字符串。

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

【讨论】:

  • 非常感谢@enriqg9
【解决方案2】:

这是工作小提琴: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>

【讨论】:

    【解决方案3】:

    您不能更改子组件中的道具。 您应该使用$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>
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 2020-08-04
      • 2021-01-18
      • 2018-02-02
      • 2018-08-03
      • 2019-01-21
      • 2017-02-27
      • 1970-01-01
      相关资源
      最近更新 更多