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
分类:
Pinia
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步