假设你有一个Vue组件,组件中有一个列表数据list,你要将从API中获取的数据添加到list中。你可以采用以下方法:
fetchData),用于从API中获取数据:- methods: {
- fetchData() {
- // 通过axios库发送HTTP请求从API中获取数据
- axios.get('/api/data')
- .then(response => {
- // 在获取到数据后将数据添加到list中
- this.list.push(...response.data);
- })
- .catch(error => {
- console.log(error);
- });
- }
- }
created中调用fetchData方法,以在组件创建后获取数据并添加到列表中:- created() {
- this.fetchData();
- }
v-for指令循环遍历list,并将其中的数据渲染出来:- <template>
- <ul>
- <li v-for="item in list" :key="item.id">
- {{ item.name }}
- </li>
- </ul>
- </template>
这样,当Vue组件加载后,会自动调用fetchData方法,从API中获取数据并添加到list中。然后,模板中的v-for指令会遍历list,将其中的数据渲染出来。