conuter.ts

<template>
  <div>
    <!-- 显示当前的计数 -->
    <p>Count: {{ count }}</
    <!-- 显示计算的双倍计数 -->
    <p>Double Count: {{ doubleCount }}</p>
    <!-- 点击按钮以增加计数 -->
    <button @click="increment">Increment</button>
    <!-- 显示从API获取的列表项 -->
    <ul>
      <li v-for="item in list" :key="item.id"> {{ item.id }} {{ item.name }} </li>
    </ul>
  </div>
</template>

<script setup>
import { useCounterStore } from './stores/conuter'; // 导入store
import { storeToRefs } from 'pinia'; // 导入响应式状态属性的帮助函数
import { onMounted } from 'vue'; // 导入生命周期钩子

const counterStore = useCounterStore(); // 初始化store

// 从store中解构响应式属性
const { count, doubleCount, list } = storeToRefs(counterStore);
// 从store中解构方法
const { increment, getList } = counterStore;

// 组件挂载时获取列表数据
onMounted(() => {
  getList();
});
</script>

 App.vue

import { defineStore } from 'pinia'; // 导入Pinia的defineStore函数
import { computed, ref } from 'vue'; // 导入Vue的响应式工具
import axios from 'axios'; // 导入用于HTTP请求的Axios

export const useCounterStore = defineStore('counter', () => {
    // 定义一个响应式状态属性
    const count = ref(0);

    // 定义一个方法来增加计数
    const increment = () => {
        count.value++;
    };

    // 定义API URL
    const APi_URL = 'http://geek.itheima.net/v1_0/channels';

    // 定义一个响应式状态属性来存储列表
    const list = ref([]);

    // 定义一个方法从API获取列表数据
    const getList = async () => {
        const res = await axios.get(APi_URL);
        list.value = res.data.data.channels;
    };

    // 定义一个计算属性来获取双倍的计数
    const doubleCount = computed(() => count.value * 2);

    // 返回状态属性和方法
    return {
        count,
        increment,
        doubleCount,
        list,
        getList
    };
});

目录结构如图:

运行截图

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部