用Rails.5.2+ Vue.js做 vue-todolist app
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 })
用Rails.5.2+ Vue.js做 vue-todolist app