0

When i push a value in my array with VueJS, chrome display it but just after my web page is reloading.

let vm = new Vue ({
    el:'#app2',

    data: {
        people: ['Robert', 'Pablo', 'Lucas', 'Teban']
    },

    methods: {
        addPerson: function() {
            this.people.push('Maxime')   
        },
    }
})

    <section id="app2" style="margin-top: 100px">
        <p>{{people}}</p>
        <form>
            <button v-on:click='addPerson'>Ajouter une personne</button>
        </form>
    </section>
4
  • can you share more code. There doesnt seem to be much problem here Commented Feb 8, 2019 at 17:10
  • Are you sure the element triggering addPerson() is not reloading the page? E.g. it is a <button> or an <a> element and you didn't use event.preventDefault() (or set type="button" for the former?
    – Terry
    Commented Feb 8, 2019 at 17:10
  • <section id="app2" style="margin-top: 100px"> <p>{{people}}</p> <form> <button v-on:click='addPerson'>Ajouter une personne</button> </form> </section>
    – MydroX
    Commented Feb 8, 2019 at 17:12
  • As @Terry said, if you are using a button click event, you have to set the type="button".
    – xcopy
    Commented Feb 8, 2019 at 17:13

1 Answer 1

1

Your problem is that your <button> element is submitting the form. When it's type is not defined, it is set to submit by default, which causes the form to submit (and therefore reloading/refreshing your page):

submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.

To prevent that, you can use:

<button v-on:click='addPerson' type='button'>Ajouter une personne</button>

Or use the prevent event modifier on the click directive:

<button v-on:click.prevent='addPerson'>Ajouter une personne</button>

Or invoke event.preventDefault() directly in the method:

methods: {
    addPerson: function(e) {
        e.preventDefault();
        this.people.push('Maxime')   
    },
}
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.