假定我們有一個(gè)需求,一開始通過mounted()將一個(gè)字符串渲染在頁面上,但是我們經(jīng)過操作后修改了數(shù)據(jù)并且需要將得到的結(jié)果重新異步渲染到頁面中去,而不是跳轉(zhuǎn)刷新頁面來重新渲染
首先模板中data()中定義數(shù)據(jù),并且要將定義的數(shù)據(jù)顯示出來
<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里的函數(shù)來獲取后臺(tái)的數(shù)據(jù)
methods:{  async click(){    let {status,data:{text}} = await self.$axios.post('/updateText',{      text,      newText    })       this.text = text;  }  }服務(wù)端的接口如下
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 }})這里有個(gè)重點(diǎn)!
獲取頁面?zhèn)鬟^來的參數(shù)時(shí)必須使用結(jié)構(gòu)賦值的方法獲取,不然獲取到的為一個(gè)Object,查詢將會(huì)出錯(cuò)!
雙向綁定在這里的體現(xiàn)是:一開始通過mounted()將數(shù)據(jù)渲染到模板中,然后調(diào)用函數(shù)通過服務(wù)端的updateText接口改變數(shù)據(jù),在updateText接口中更新完數(shù)據(jù)后,執(zhí)行一遍查詢,將查詢結(jié)果返回到觸發(fā)的函數(shù)中。并在該函數(shù)中修改data()中text的值達(dá)到數(shù)據(jù)雙向綁定的效果
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注