pinia学习

 

 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
    };
});

目录结构如图:

运行截图

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值