当前位置:   article > 正文

Nuxt.js 数据双向绑定

nuxt 绑定全部函数

假定我们有一个需求,一开始通过mounted()将一个字符串渲染在页面上,但是我们经过操作后修改了数据并且需要将得到的结果重新异步渲染到页面中去,而不是跳转刷新页面来重新渲染

首先模板中data()中定义数据,并且要将定义的数据显示出来

  1. <template>
  2. <div>
  3. <span @click="click">{{ text }}</span>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data(){
  9. return {
  10. text: '',
  11. newText: '1'
  12. }
  13. },
  14. async mounted(){
  15. let {status,data:{text}} = await self.$axios.post('/getText');
  16. this.text = text;
  17. }
  18. }
  19. </script>

然后我们通过methods里的函数来获取后台的数据

  1. methods:{
  2. async click(){
  3. let {status,data:{text}} = await self.$axios.post('/updateText',{
  4. text,
  5. newText
  6. })
  7. this.text = text;
  8. }
  9. }

服务端的接口如下

  1. router.get('/getText', async (ctx) => {
  2. let text= await Text.find();
  3. ctx.body = {
  4. text
  5. }
  6. }
  7. router.post('/updateText', async (ctx) => {
  8. const {text,newText} = ctx.request.body;
  9. let oldVal = text;
  10. let newVal = newText;
  11. let ncomment = await Comment.updateOne(oldVal,newVal);
  12. let text= await Text.find();
  13. ctx.body={
  14. text
  15. }
  16. })

这里有个重点!
获取页面传过来的参数时必须使用结构赋值的方法获取,不然获取到的为一个Object,查询将会出错!

双向绑定在这里的体现是:一开始通过mounted()将数据渲染到模板中,然后调用函数通过服务端的updateText接口改变数据,在updateText接口中更新完数据后,执行一遍查询,将查询结果返回到触发的函数中。并在该函数中修改data()中text的值达到数据双向绑定的效果

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/971386
推荐阅读
相关标签
  

闽ICP备14008679号