我如何填充 axios 获取数据数组并将其传递给 Vuejs 组件道具以在组件中进行列表渲染 [英] how can i populate an axios get data array and pass it to a Vuejs component props to do list rendering in the component

查看:34
本文介绍了我如何填充 axios 获取数据数组并将其传递给 Vuejs 组件道具以在组件中进行列表渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一个名为 upload-csv 的组件

Vue.component('upload-csv',{道具:['客户名'],模板:`<ul><li v-for="clientname in clientnames">{{ clientname.name }}</li>`});

然后是一个 Vue 实例

new Vue({el:"#upload-csv-component",数据:{loadurl:'http://localhost/startup/public/index.php/loadnames',客户名称:[]},安装:功能(){axios.get(this.loadurl).then(功能(响应){this.clientnames = response.data;}).catch(函数(错误){});}});

希望这样使用

<upload-csv :clientnames="clientnames"></upload-csv>

但是列表没有渲染;我已将挂载钩子更改为 beforeMount 但列表未呈现.

请有人提出解决此问题的方法.

解决方案

使用箭头函数在 axios 请求中保持对 this 的访问:

mounted(){axios.get(this.loadurl).then((响应) => {this.clientnames = response.data})}

(关于this 上下文的好答案这里)

Given I have a component called upload-csv

Vue.component('upload-csv',{
 props:['clientnames'],
 template:`
    <ul>
       <li v-for="clientname in clientnames">{{ clientname.name }}</li>
    </ul>
 `
});

Then a Vue Instance

new Vue({
 el:"#upload-csv-component",
 data:{
  loadurl:'http://localhost/startup/public/index.php/loadnames',
  clientnames:[]
 },
 mounted:function(){
  axios.get(this.loadurl)
  .then(function(response){
   this.clientnames = response.data;
  })
  .catch(function(error){});
 }
});

Wish to use it this way

<div id="upload-csv-component">
  <upload-csv :clientnames="clientnames"></upload-csv>
</div>

But the list is not rendering; I have changed mounted hook to beforeMount yet the list is not rendering.

Please can someone suggest a way to solve this problem.

解决方案

Use an arrow function to keep access to this inside the axios request:

mounted(){
  axios.get(this.loadurl)
  .then((response) => {
    this.clientnames = response.data
  })
}

(great answer here about this context)

这篇关于我如何填充 axios 获取数据数组并将其传递给 Vuejs 组件道具以在组件中进行列表渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆