Rails5.2+Vue.js完成Lists(curd)
注意: Edit/update使用SPA(不换页)的方法完成。点击文字出现一个输入框和按钮。
我的git: https://github.com/chentianwei411/vue-lists
app/javascript/pack/application.js
lists.vue
添加了方法
- 在new Vue创建实例的时候添加了hook created方法,钩子方法调用了fetchLists方法用于得到数据:
- fetchLists方法,其实对应(Controller#get)
- addLine (Controller#create)
- changeLine方法, 用于配合v-show的显示/隐藏功能
- deleteLine: (Controller#destroy)
- updateLine (Congroller#update)
addLine: function() {
this.$http.post(‘/lists.json‘, { item: this.checkInput }, {}).then(response => {
this.fetchLists(), this.checkInput = ‘‘
}).catch(function(error) {
console.log(‘Got a problem‘ + error)
})
}
catch用于全程出错后,对错误的处理。
deleteLine(id) {
this.$http.delete(`/lists/${id}.json`).then(response => {
this.fetchLists()
})
disabled属性:
当true时,元素不能用。包括<button><input><select><textarea><options>
<input type=‘text‘ v-model=‘line‘ class=‘form-control‘ autofocus="true">
<button v-on:click=‘addLine()‘ class=‘btn btn-primary‘ :disabled="!line.length" >Add line</button>
line是string。调用!line.length方法, 结果有2种:
- !0 > true line是空字符串。
- !12 > false line不为空。
JS的Array的map方法
例子:
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map((old) => { old.secondname = ‘hello‘; return old})
结果
[
{firstname: "Malcom", lastname: "Reynolds", secondname: "hello"},
{firstname: "Kaylee", lastname: "Frye", secondname: "hello"},
{firstname: "Jayne", lastname: "Cobb", secondname: "hello"}
]
arr.map(function(old) { return new })