欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Nuxt.js 數(shù)據(jù)雙向綁定的實(shí)現(xiàn)

 更新時(shí)間:2019年02月17日 11:03:01   作者:rirmk  
這篇文章主要介紹了Nuxt.js 數(shù)據(jù)雙向綁定的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

假定我們有一個(gè)需求,一開始通過mounted()將一個(gè)字符串渲染在頁(yè)面上,但是我們經(jīng)過操作后修改了數(shù)據(jù)并且需要將得到的結(jié)果重新異步渲染到頁(yè)面中去,而不是跳轉(zhuǎn)刷新頁(yè)面來重新渲染

首先模板中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)!

獲取頁(yè)面?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ù)雙向綁定的效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論