3

Here is a simple Vue 2.0 form component. It consists of a number input and a button, e.g.:

enter image description here

Note that the value of the input is tied to the component's data using v-model. buttonText is passed in as a prop.

What's the best way to pass a default value into the form, so that it initially renders with a value other than 10?

  • Using props doesn't seem to be the right way to do it because then v-model no longer works properly.
  • However, data can't be passed in the way props can, as far as I can tell from Vue documentation.

.

<template>
    <form v-on:submit.prevent="onSubmit">
      <input v-model="amount" type="number" min="1" max="20"></input>
      <button type="submit">{{ buttonText }}</button>
    </form>
</template>

<script>
  export default {
    props: [ 'buttonText' ],
    data: function() {
      return {
        amount: 10
      }
    },
    methods: {
      onSubmit: function() {
        this.$emit("submit", parseInt(this.amount) );
      }
    }
  }
</script>
3
  • You can use props. It won't give any issue. Commented Sep 12, 2017 at 12:25
  • 1
    @SureshVelusamy No, you can't. Vue throws a warning that you shouldn't be editing props because they will be overwritten if the parent component is re-rendered. Commented Sep 12, 2017 at 12:44
  • Yep . As #vuejs says we can use computed property :) Commented Sep 12, 2017 at 12:55

1 Answer 1

4

You can pass in a prop (say initialAmount) and reference that when initializing the amount value in the data function:

export default {
  props: {
    buttonText: { type: String },
    initialAmount: { type: Number, default: 10 },
  },
  data: function() {
    return {
      amount: this.initialAmount
    }
  },
  methods: {
    onSubmit: function() {
      this.$emit("submit", parseInt(this.amount) );
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.