pinia入门案例-获取频道分类列表并渲染
使用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>
本文来自博客园,作者:蕝戀,转载请注明原文链接:https://www.cnblogs.com/juelian/p/17626541.html