Vue3项目Pinia-异步action示例

已经用npm init vue@latest创建了一个空的Vue3项目,
使用npm install pinia安装了pinia,
使用npm install axios安装了依赖。

在这里插入图片描述

项目的package.json文件:

{
  "name": "vue-pinia",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "axios": "^1.6.8",
    "pinia": "^2.1.7",
    "vue": "^3.4.21"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.0.4",
    "vite": "^5.2.8"
  }
}

项目src目录下的main.js文件修改为:
在这里插入图片描述

main.js:

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'

// 导入createPinia
import { createPinia } from 'pinia'

// 执行createPinia方法,得到实例
const pinia = createPinia()

// 将pinia实例作为插件注册到应用中
createApp(App).use(pinia).mount('#app')

在src目录下新建一个stores目录,在该目录新建一个counter.js文件:
在这里插入图片描述

counter.js:

import { computed, ref } from 'vue'
// 导入方法 defineStore
import { defineStore } from 'pinia'
import axios from 'axios'

const API_URL = 'http://geek.itheima.net/v1_0/channels'

// 第一个参数是sotore的id,必须唯一
// 第二个参数是一个函数
export const useCounterStore = defineStore('counter', () => {
    // 定义数据,就是state
    const count = ref(0)

    // 定义修改数据的方法,就是action。既支持同步,也支持异步
    const increment = () => {
        count.value++
    }

    // getter定义
    const doubleCount = computed(() => count.value * 2)

    // 定义异步action
    const list = ref([])
    const getList = async () => {
        const res = await axios.get(API_URL)
        list.value = res.data.data.channels
    }

    // 以对象的方式return,供组件使用
    return {
        count,
        doubleCount,
        increment,
        list,
        getList
    }
})

App.vue:
在这里插入图片描述

App.vue:

<script setup>
// 导入useCounterStore方法
import { useCounterStore } from '@/stores/counter'
import { onMounted } from 'vue';

// 执行方法,得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore)

onMounted(() => {
    counterStore.getList()
})
</script>

<template>
    <button @click="counterStore.increment">{{ counterStore.count }}</button>
    {{ counterStore.doubleCount }}

    <ul>
        <li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li>
    </ul>
</template>

<style scoped></style>

运行程序:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值