Nuxt.js 資料雙向繫結
假定我們有一個需求,一開始通過mounted()將一個字串渲染在頁面上,但是我們經過操作後修改了資料並且需要將得到的結果重新非同步渲染到頁面中去,而不是跳轉重新整理頁面來重新渲染
首先模板中data()中定義資料,並且要將定義的資料顯示出來
<template> <div> <span @click="click">{{ text }}</span> </div> </template> <script> export default { data(){ return { text: '', newText: '1' } }, async mounted(){ let {status,data:{text}} = await self.$axios.post('/getText'); this.text = text; } } </script>
然後我們通過methods裡的函式來獲取後臺的資料
methods:{ async click(){ let {status,data:{text}} = await self.$axios.post('/updateText',{ text, newText }) this.text = text; } }
服務端的介面如下
router.get('/getText', async (ctx) => { let text= await Text.find(); ctx.body = { text } } router.post('/updateText', async (ctx) => { const {text,newText} = ctx.request.body; let oldVal = text; let newVal = newText; let ncomment = await Comment.updateOne(oldVal,newVal); let text= await Text.find(); ctx.body={ text } })
這裡有個重點!
獲取頁面傳過來的引數時必須使用結構賦值的方法獲取,不然獲取到的為一個Object,查詢將會出錯!
雙向繫結在這裡的體現是:一開始通過mounted()將資料渲染到模板中,然後呼叫函式通過服務端的updateText介面改變資料,在updateText介面中更新完資料後,執行一遍查詢,將查詢結果返回到觸發的函式中。並在該函式中修改data()中text的值達到資料雙向繫結的效果