.vue 单文件组件,fetch异步怎么更新视图数据?

.vue 单文件代码 例如

<template>
<div class="content nsr-card-bg">

  <div class="nsr-card" v-for="res in result">
    <img v-bind:src="res.img" alt="">
    <p>{{res.content}}</p>
    <div class="nsr-card-user-info">
      <p>
        <img v-bind:src="res.avatar" alt="">
        <span>from</span>{{res.nickname}}
      </p>
      <p class="fa fa-map-marker">{{res.address}}</p>
    </div>
  </div>

</div>
  
</template>

<script>

  var data = [];
  
  fetch('/server.php')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    data = json;
    console.log(json);
  }).catch(function(ex) {
    console.log(ex);
  });

  module.exports={
    data:function () {
      return {
        result : data
      }
    }
  }
</script>

谢谢

阅读 3.5k
1 个回答
<script>
  module.exports= {
    data:function () {
      return {
        result: []
      };
    },
    ready() {
        var self = this;
        fetch('/server.php')
          .then(function(response) {
            return response.json()
          }).then(function(json) {
            self.result = json;
          }).catch(function(ex) {
            console.log(ex.stack);
          });
    }
  }
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题