【发布时间】:2019-12-03 22:53:36
【问题描述】:
我正在学习 Vue.js,并且正在构建一个桶列表应用程序。我遇到的问题是,当我添加一个新项目时,我的输入被清除了,但是当我开始添加一个新项目时,前一个项目也会更新。
HTML
<div class="container">
<add-form></add-form>
<bucketlist></bucketlist>
</div>
AddForm.vue
<template>
<div>
<h2>
Add new item
</h2>
<form method="post" @submit.prevent="formSubmit">
<div>
<input type="text" placeholder="Title" v-model="title">
</div>
<div>
<label for="">Status</label>
<input type="checkbox" v-model="status">
</div>
<div>
<input type="submit" value="Save">
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
title: '',
status: false,
}
},
methods: {
formSubmit(event) {
axios.post('/add-item', this.$data)
.then((response) => {
this.$eventBus.$emit('newitem', this.$data)
})
// this.title = '';
event.target.reset();
},
}
}
</script>
Bucketlist.vue
<template>
<div class="bucketlist">
<div v-for="bucket in bucketlist" class="bucketitem">
<h3>
{{ bucket.title }}
</h3>
<input type="checkbox" :id="bucket.id"
:checked="bucket.status ? true : false"
@click="updateStatus">
</div>
</div>
</template>
<script>
export default {
data() {
return {
bucketlist: []
}
},
methods: {
updateStatus(value) {
axios.post('/update-status/'+value.target.id, this.$data);
}
},
mounted() {
axios.get('/bucketlist')
.then(response => (this.bucketlist = response.data.bucketlist));
this.$eventBus.$on('newitem', (data) => {
this.bucketlist.push(data);
});
}
}
</script>
我尝试了this.title = '',但在提交请求时收到错误Column 'title' cannot be null。
这不是添加新项目并保持 Vue 反应性的正确方法吗?
我制作了一个小(而且很糟糕)的 GIF 来说明我的问题。
【问题讨论】:
-
从逻辑的角度来看,你的例子看起来很像非常常见的 Todo MVC“应用程序”,当然有一个 vue.js 的实现,例如看看这里,看看为它实现的那种模式:github.com/tastejs/todomvc/tree/gh-pages/examples/vue
标签: vue.js vuejs2 vue-component