Nuxt.js data bidirectional binding

Time:2019-5-30

Suppose we have a requirement to render a string on the page initially by mounted (), but we modified the data after operation and needed to render the results asynchronously to the page instead of skipping the refresh page to re-render.

First, data is defined in data () in the template, and the defined data is displayed.

<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>

Then we use the functions in methods to get the background data.

methods:{
    async click(){
        let {status,data:{text}} = await self.$axios.post('/updateText',{
            text,
            newText
        })
     
        this.text = text;
    }
    
}

The server interface is as follows

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
  }
})

Here’s a point!
When getting the parameters from the page, we must use the method of structure assignment to get them. Otherwise, if we get an Object, the query will be wrong!

Bi-directional binding is embodied here as follows: first, data is rendered into the template by mounted (), then the calling function changes the data through the updateText interface of the server, after updating the data in the updateText interface, the query is executed once, and the query result is returned to the triggered function. In this function, the value of text in data () is modified to achieve the effect of bidirectional data binding.

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]