简体   繁体   English

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

[英]How to pass parameter to a Vue component to initiate components instance

I am very new to the Vue.我对 Vue 很陌生。 I am trying to learn how to create and re-use Vue components.我正在尝试学习如何创建和重用 Vue 组件。 The initial data passed to a component is not updated on an click event.传递给组件的初始数据不会在单击事件上更新。 Here is my code (full version at https://jsfiddle.net/gpawel/486ysvxj/33/ ) What I am doing doing wrong?这是我的代码(完整版在https://jsfiddle.net/gpawel/486ysvxj/33/ )我做错了什么? Thank you.谢谢你。

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

Here is the working fiddle: https://jsfiddle.net/68p1u9ks/这是工作小提琴: 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>'
})

I think you need to maintain state inside the button-counter component.我认为您需要在button-counter组件内维护 state 。 Also rename the count prop to initial-count .还将count属性重命名为initial-count

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

See your updated fiddle .查看您更新的小提琴 You are directly mutating the count property, save it as a data first and mutate the internalCount.您正在直接改变 count 属性,首先将其保存为数据并改变 internalCount。 Also, use a : to cast the prop to a Number and not a string.此外,使用:将道具转换为数字而不是字符串。

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

You can not change props in child component.您不能更改子组件中的道具。 You should use $emit to change props:您应该使用$emit来更改道具:

parent component:父组件:

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

and child component:和子组件:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM