1

I am trying to use the v-model and it is not picking up what I am trying to bind it from the data object which is 'quote'. In addition my @click won't recognize my function 'createNew' for some reason when trying to use the $emit when passing props.

I have looked at the documentation on VueJS and also been searching around the web and tried other things such as maybe using a v-bind along with the @click but that doesn't seem to work. I'm stumped on why it is not working.

<template>
    <div class="row">
        <form>
            <div class="col-sm-8 col-sm-offset-2 col-xs-12 col-md-6 col-md-offset-3 form-group">
                <label>Quote</label>
                <textarea class="form-control" rows="3" v-model="quote"></textarea>
            </div>
            <div class="col-sm-8 col-sm-offset-2 col-xs-12 col-md-6 col-md-offset-3 form-group">
                <button class="btn btn-primary" @click ="createNew">Add Quote</button>
            </div>
        </form>
    </div>
</template>

<script>
    export default {
        data: function () {
            return {
                quote: ''
            };
        },
        methods: {
            createNew(){
                this.$emit(quoteAdded, this.quote);
                this.quote = '';
            }
        }
    }

I expect v-model to register the data 'quote' and the @click to recognize my 'createNew' function which it isn't at all.

Phil
  • 157,677
  • 23
  • 242
  • 245
brianmsantos
  • 67
  • 1
  • 11
  • There will be an error in your console for the undefined variable `quoteAdded`. You probably meant to use a string, ie `this.$emit('quoteAdded', this.quote)` – Phil Apr 17 '19 at 05:10
  • I'd also remove the space between `@click` and `=` – Phil Apr 17 '19 at 05:11

1 Answers1

0

Given you have a <form> and a submit <button>, your form will be submitting normally.

You could prevent the default event action on the button click (using @click.prevent="createNew"), use type="button" or (and this is my preference), listen for the submit even on the <form>.

There's also potential issues using camel-cased event names like "quoteAdded". It's highly recommended you always use kebab-case. See https://v2.vuejs.org/v2/guide/components-custom-events.html#Event-Names

Tidying up your code a little, it looks like this

<template>
  <div class="row">
    <form @submit.prevent="createNew">
      <!-- and so on -->
        <button class="btn btn-primary" type="submit">Add Quote</button>
      <!-- snip -->
    </form>
  </div>
</template>
methods: {
  createNew () {
    this.$emit('quote-added', this.quote)
    this.quote = ''
  }
}

and in your parent template

<your-component @quote-added="handleQuoteAdded">

Demo ~ https://jsfiddle.net/kc0wfydp/

tony19
  • 125,647
  • 18
  • 229
  • 307
Phil
  • 157,677
  • 23
  • 242
  • 245