使用pinia的action异步获取频道分类列表数据并渲染到页面中。
接口:
GET请求,http://geek.itheima.net/v1_0/channels
store/channel.js
import {defineStore} from 'pinia'
import {ref, computed} from "vue"
import axios from 'axios'
export const useChannelStore = defineStore('Channel', () => {
// 定义state
const channelList = ref([])
// 定义actions
const getChannelList = async () => {
const resp = await axios.get('http://geek.itheima.net/v1_0/channels')
console.log(resp);
// 赋值给state
channelList.value = resp.data.data.channels
}
return {
channelList,
getChannelList,
}
})
app.vue
<script setup>
// 1. 导入store
const channelStore = useChannelStore();
</script>
<template>
<button @click="channelStore.getChannelList()">获取新闻列表</button>
<ul>
<li v-for="item in channelStore.channelList" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
标签:axios,const,入门,渲染,channelList,channels,pinia,import
From: https://www.cnblogs.com/juelian/p/17626541.html