不能在Vue上更改道具的名称?

时间:2018-01-26 04:31:21

标签: javascript vue.js vuejs2

我是VueJS的新手,并试图在组件上遵循v模型实现 example here

<template>
    <div class="date-picker">
        Month: <input type="number" ref="monthPicker" :value="value.month" @input="updateDate()" />
        Year: <input type="number" ref="yearPicker" :value="value.year" @input="updateDate()" />
    </div>
</template>

<script>
    export default {
        props: ['value'],

        methods: {
            updateDate() {
                this.$emit('input', {
                    month: +this.$refs.monthPicker.value,
                    year: +this.$refs.yearPicker.value
                })
            }
        }
    };
</script>

父母:

<template>
    <div class="wrapper">
        <date-picker v-model="date"></date-picker>
        <p>
            Month: {{date.month}}
            Year: {{date.year}}
        </p>
    </div>
</template>

<script>
    import DatePicker from './DatePicker.vue';

    export default {
        components: {
            DatePicker
        },

        data() {
            return {
                date: {
                    month: 1,
                    year: 2017
                }
            }
        }
    })
</script>

我想知道为什么我不能改变道具的名称:[&#39;价值&#39;]道具:[&#39; abc&#39;] 并改变

Month: <input type="number" ref="monthPicker" :value="abc.month" @input="updateDate()" />

我收到错误:TypeError:无法读取属性&#39; month&#39;未定义的

2 个答案:

答案 0 :(得分:0)

您是否更改了其父组件中的属性?

为父级:

 <template>
  <div id="parent">
   <div is="test" :abc="YearMonth" @input="receiveValueFromChild"></div>
  </div>
</template>

<script>
import test from "./test.vue";

export default {
  components: {
    test: test
  },
  name: "index",
  data() {
    return {
      YearMonth: { month: 1, year: 2018 }
    };
  },
  methods: {    
    receiveValueFromChild: function(val) { //here will be toggled by childComponent
      console.log(val);
    }
  }
};
</script>

childCompoent:

<template>
    <div class="date-picker">
        <span>Month: </span><input type="number" v-model="abc.month" @input="updateDate()" />
        <span>Year: </span><input type="number" v-model="abc.year" @input="updateDate()" />
    </div>
</template>

<script>
export default {
  props: ["abc"],

  methods: {
    updateDate() {
      this.$emit("input", { //sent value to parentComponent
        month: this.abc.month,
        year: this.abc.year
      });
    }
  }
};
</script>

答案 1 :(得分:0)

您所看到的是使用onResume的副作用。

如果您将道具定义更改为:

props: ['value']

您会看到您可以将道具名称更改为您喜欢的任何名称。

工作小提琴:https://jsfiddle.net/o5uLxdhs/13/