How to make adding reviews? When submitting a form, I want to add a review, display it on the page and clear the fields in the form. How can this be implemented?

My option: In beforeCreated get all the reviews from the server and display them on the page. Create an array in the store and write data to it after displaying the form. clear the field will not work. How can I solve this problem? The code for my version is below:

export default { data() { return { review: { userName: '', reviewText: '' } }, methods: { sendReview() { this.$store.dispatch('postReview', this.review) } }, computed: { reviews() { return this.$store.getters.getReviews } }, beforeCreate() { this.$store.dispatch('loadReviews') } } // vuex store import Vue from 'vue'; export default { state: { reviews: [] }, getters: { getReviews(state) { return state.reviews } }, mutations: { updateReviews(state, data) { state.reviews = data; }, addNewReview(state, data) { state.reviews.push(data); }, }, actions: { loadReviews({ commit }) { Vue.http.get('url.json') .then(res => { return res.json() }) .then(data => { commit('updateReviews', data) }) }, postReview({ commit }, payload) { Vue.http.post('url', payload) .then(() => { commit('addNewReview', payload) }) } } } 
 <template> <div class="container"> <h1>Отзывы</h1> <form @submit.prevent="sendReview"> <input v-model="review.userName" type="text" placeholder="Имя" > <textarea v-model="review.reviewText" placeholder="Отзыв" cols="30" rows="3"> </textarea> <input type="submit" > </form> <ul> <li v-for="item in reviews"> <h2>{{item.userName}}</h2> <p>{{item.reviewText}}</p> </li> </ul> </div> </template> 

    1 answer 1

    Solved the problem as follows: i.e. now the data does not depend on v-model

     class Review { constructor(user, text) { this.userName = user this.reviewText = text } } sendReview() { const review = { userName: this.review.userName, reviewText: this.review.reviewText } this.$store.dispatch('postReview', review) .then(() => { this.review.userName = ''; this.review.reviewText = ''; }) }