第一次使用Vue js的用户,尝试通过构建一个小型博客/文章系统来学习,用户可以在其中添加文章,并且该文章将显示在页面上(并存储在json中)
到目前为止,我的代码: 我有一个可以显示的Json数组。 我有一个可以在其中添加名称和姓氏的表格,并将其显示在页面上。
下一步: 我希望单击我的按钮,并将新名称和姓氏添加到文件中的json对象中。
问题: 如何单击按钮并将其添加到用户数据数组中?
我的代码: Hello.vue
<template>
<div class="justify-content-center align-items-center container ">
<div class="row">
<div class="col-12 align-content-center">
<h2>Total articles: {{ users.length }}</h2>
<ul class="list-group">
<li class="list-group-item" v-for="user in users">
<div class="d-flex w-100 justify-content-between">
<h5>{{user.firstname}} {{user.lastname}}</h5>
<small>3 days ago (todo)</small>
</div>
<div class="text-justify">
<p>artical body test here (todo)</p>
<small>Author (todo)</small>
</div>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-12 align-content-center">
<form v-on:submit="sub" action="#" method="post">
<div class="form-group">
<div class="col-6">
<label>Add first name:</label>
<b-form-input type="text" v-model="input_val_firstName" placeholder="Enter your first name"></b-form-input>
</div>
<div class="col-6">
<label>Add second name:</label>
<b-form-input type="text" v-model="input_val_secondName" placeholder="Enter your second name"></b-form-input>
</div>
<div class="col-6">
<button type="submit" class="btn btn-primary">Add article</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-12 align-content-center">
<h2>Preview article</h2>
<strong>Name:</strong>
<span v-text="input_val_firstName"></span>
<span v-text="input_val_secondName"></span>
<h3>log:{{log}}</h3>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
},
name: 'Hello',
data() {
return {
msg: 'Display articles',
secondmsg: 'This is a blog built in Vue.js.',
log: "",
users: [
{
firstname: 'Sebastian',
lastname: 'Eschweiler'
},
{
firstname: 'Bill',
lastname: 'Smith'
},
{
firstname: 'Tom',
lastname: 'bull'
},
{
firstname: 'John',
lastname: 'Porter'
}
],
input_val_firstName: '',
input_val_secondName: '',
counter: 0
}
}
}
</script>
答案 0 :(得分:2)
只需添加一种添加用户的方法即可,这应该可行:
addUser: function() {
this.users.push({
firstname: this.input_val_firstName,
lastname: this.input_val_secondName
})
// assuming you'd like to clear the input-box fields after adding the user
this.input_val_firstName = ''
this.input_val_secondName = ''
}