Vue.js 在 v-for 中使用方法

新手上路,请多包涵

我想在我的 Vue 组件中的 v-for 中运行一个方法。例子:

 <div v-for="(foo,index) in bar">
      <p>{{myMethod(foo,index)}}</p>
</div>

当我这样做时,p-tag 只是保持为空。这是我的方法(使用 axios 调用):

  myMethod:function(foo,index) {
    axios.get('/myAjaxCall')
    .then((response)=> {
        //works perfectly
        alert(response.data);
        return response.data;

    })
    .catch(function (error) {
        console.error(error);
    });
   },
 }

当我 alert( SomethingWithFooAndIndex) 时,浏览器显示的正是我所需要的。当我删除 axios 调用时,该方法似乎有效

谢谢!

原文由 Sander Van Keer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 528
1 个回答

我认为您不应该在 myMethod v-for

axios 是异步的

Try to do myMethod with bar in another method, get a data newbar , you can render the newbar

<div v-for="(foo, index) in dataBar"> <p>{{otherSimpleMethod(foo, index)}}</p> </div>

  1. 在数据中添加 dataBar
  2. myMethod 变量 bar 在另一种方法 newMethod
  3. 更新 dataBar (axios响应)在 newMethod
  4. newMethod in mounted (我猜你想在页面加载后做这个)

或者你可以试试 nextTick

顺便说一句,标题 Vue.js Use mounted in v-for ???也许 Vue.js Use method in v-for ???

原文由 Xiao Da 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏