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>
posted @ 2023-08-13 14:26  蕝戀  阅读(137)  评论(0编辑  收藏  举报