iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 14
0
Modern Web

使用Vue.js製作個人blog系列 第 14

【Day 14】頁面:新增-4

  • 分享至 

  • twitterImage
  •  

vue存檔-post


現在要製作 vue的存檔語法
將使用一個叫做「vue-resource」的套件
這套套件的快速入門語法就是這樣:(範例)

{
  // GET /someUrl
  this.$http.get('/someUrl').then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}

由於傳遞值到後臺,習慣上是用post,因此把上方的範例改成下面這樣的格式:

this.$http.post("../add/data", {
    user: "eyelash"
    }
).then((response) => {
    console.log(JSON.parse(response.data))
    alert("success")
},
(response) => {
    console.log("ERROR:",response)
})

簡單說明:
post表示說使是用HTTP協定中的「post」的方法,即表示不用URL的方式傳遞資料,而是用封包的方式傳。後面的參數依照官方所言/someUrl(我的範例則是:../add/data)是說要資料傳遞之目的地;再後面是指所要傳遞的參數名稱與值。然後.then((response)=> {// success callback}則是當後面處理完成且沒有錯誤後的處理內容。這邊有個回傳的 response,而動作在大括號「{}」內進行處理。在我這邊的範例是呼叫一個log把回傳的資料用 JSON方法顯示顯示。
後面的,(response) => {// error callback})就是說當在這個/someUrl處理過程有錯誤,將會跑到這個error function,並且有個回傳值 response。是要看記錄,還是顯示給使用者看,所有的後續行為都在這個部分進行處理。。

因此,用 vue-resource我們可以把資料順利的傳到後臺,並且有效的處理回傳結果。在本篇我們的程式的觸發點就是在button這邊,因為 vue會持續監聽,由v-on:click被點擊的事件觸發其動作。當被觸發的時候將執行add的這個方法,也就是我們要在 vuemethods撰寫的功能:

add: function(){
    this.$http.post("../add/data", {
        Title: this.title,
        Content: this.content
    }
    ).then((response) => {
        console.log(JSON.parse(response.data))
    },
    (response) => {
        console.log("ERROR:",response)
    })
}

說明
首先add這個function是在methods裡面,前面是名稱,後面「:」之後是內容,而這個add是一個function,是個不帶有參數的function。而「{}」後面就是function的內容,也就是 vue-resourc的語法。裡面有兩個參數TitleContent,分別由this.titlethis.content取得網頁中欄位的資訊。後面成功則顯示回傳值的 JSON格式;如果錯誤則顯示錯誤訊息。

這樣就是簡單的前台傳遞方式!至於後臺接收,晚點就會介紹囉~


補上本篇的script

var vm = new Vue({
    el: "#editor",
    data: {
        content: "# test",
        title: "123"
    },
    computed: {
        compiledMarkdown: function () {
            return marked(this.content, { sanitize: true })
        }
    },
    methods: {
        update: _.debounce(function (e) {
            this.content = e.target.value
        }, 300),
        add: function(){
            this.$http.post("../add/data", {
                Title: this.title,
                Content: this.content
            }
            ).then((response) => {
                console.log(JSON.parse(response.data))
            },
            (response) => {
                console.log("ERROR:",response)
            })
        }
    }
})

下一篇,繼續開發畫面


上一篇
【Day 13】頁面:新增-3
下一篇
【Day 15】頁面:後臺列表
系列文
使用Vue.js製作個人blog17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言