gpt4 book ai didi

javascript - 为什么 VueJS 在推送数组后自动重新加载?

转载 作者:行者123 更新时间:2023-12-03 00:14:05 24 4
gpt4 key购买 nike

当我使用 VueJS 在数组中推送一个值时,chrome 会显示它,但就在我的网页重新加载之后。

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>

最佳答案

你的问题是你的<button>元素正在提交表单。当它type时未定义,it is set to submit by default ,这会导致表单提交(并因此重新加载/刷新您的页面):

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.

为了防止这种情况,您可以使用:

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

或者使用 prevent event modifier关于点击指令:

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

或者调用event.preventDefault()直接在方法中:

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

关于javascript - 为什么 VueJS 在推送数组后自动重新加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54597225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com