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