pinia入门案例-获取频道分类列表并渲染

发布时间 2023-08-13 14:33:10作者: 蕝戀

使用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>