用 Vue 和 Axios 渲染列表时如何解决这个问题?

时间:2021-03-13 14:43:13

标签: vue.js axios

我在后端使用一个节点来执行查询并通过 JSON 发送数据。这个数据在前端由 axios 请求并由 Vue 渲染。数据正常到达最前面,问题是渲染列表的时候vue没有渲染。

下面我在后端发送查询代码:

routeruser.post('/tesvue', function(req, res){
   
  const teste =dadoslances.findAll()
  .then( function(resp){
    
    res.json(resp)
    return resp
  }, function(err){
    res.json({resp: "falha"})

    return err
  });

})

请求本次查询数据的Vue代码如下:

var applance = new Vue({
el: '#lancapp',
data(){
        return {
        lances: []
         }
        
},
mounted(){          
             axios
                .post('/tesvue')
                .then(response =>( this.lances=response.data))
 
      
},

updated: function () {
  setInterval(   
        axios
        .post('/tesvue')
        .then(response =>( 
                console.log(response),
                this.lances=response.data))
        
        ,5000)
} 

})

如果我把这个代码放在模板中:

<div id="lancapp" >
   
   <p>{{ lances }}</p>

  </div>

使用上面显示的代码,Vue 返回了以下以错误方式呈现的正确数据:

[ { "id": 1, "lance": "R$ 25,00", "objeto": "teste 3", "realizadorselec": null, "ncurtidas": null, "statuslance": null, "modalrel": null, "datacriacao": null, "createdAt": "2021-03-11T14:49:18.000Z", "updatedAt": "2021-03-11T14:49:18.000Z", "idusuariolancador": 1 }, { "id": 2, "lance": "R$ 200,00", "objeto": "teste 4", "realizadorselec": null, "ncurtidas": null, "statuslance": null, "modalrel": null, "datacriacao": null, "createdAt": "2021-03-11T14:49:39.000Z", "updatedAt": "2021-03-11T14:49:39.000Z", "idusuariolancador": 1 } ]

每个用户都出价想要获得一个对象,这些出价必须以列表的形式使用 Vue 动态呈现,但我无法做到这一点。有人可以帮我发现问题吗?

以下是我已经做过的一些尝试:

Tentativa 1:

<div id="lancapp" v-for="item of lances" >
   
   <p>{{item.lance}}</p>
   <p>{{item.vontade}}</p>

  </div>

Tentativa 2:

<div id="lancapp" v-for="item of lances" :key="item.id">
   
   <p>{{item.lance}}</p>
   <p>{{item.vontade}}</p>

  </div>

Tentativa 3:

<div id="lancapp" v-for="item of lances['data']" >
   
   <p>{{item.lance}}</p>
   <p>{{item.vontade}}</p>

  </div>

Tentativa 4:

 <div id="lancapp" v-for="{item, id} of lances" :key="item.id">
   
   <p>{{item.lance}}</p>
   <p>{{item.vontade}}</p>

  </div>

由于数据以简单变量的形式呈现,所以我只尝试了模板。如果有人可以提供帮助,我提前感谢您。

1 个答案:

答案 0 :(得分:1)

您必须在另一个 div 中呈现。您正在尝试在 Vue 实例的挂载点上进行渲染。

new Vue({
  el: "#app",
  data: {
    items: []
  },
  mounted() {
    fetch('https://rickandmortyapi.com/api/character/?page=1')
      .then(res => res.json())
      .then(res => {
        this.items = res.results
       })
      .catch(err => console.error(err))
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
 <div v-for="(item, key) in items" :key="key">
  <p> - {{ item.id }} : {{ item.name }} | {{ item.status }} | {{ item.species }} </p>
 </div>
</div>

如果您尝试在 Vue 实例本身上进行渲染,则会出现错误。