vue3前端开发,一篇文章看懂何谓pinia

vue3前端开发,pinia的基础练习第一节!

前言,pinia是为了取代vuex而诞生的产品,它有一些改进。去掉了之前的mutations。只有一个action,既可以支持异步,又支持同步。还提供了解构函数,可以把返回的对象内部属性和方法直接解构出来。就不需要再使用对象.属性的格式了。

下面是代码内容。


import {defineStore} from 'pinia'
import {ref,computed} from 'vue'
import axios from 'axios'

const URL_API = 'http://geek.itheima.net/v1_0/channels'
export const useCounterStore = defineStore('counter',()=>{
    const price = ref(49)
    function increament(){
        price.value++
    }
    //3 getter的模拟,使用计算属性
    const doubleCount = computed(()=> price.value*2)
    //4 定义异步操作
    const list = ref([])
    const getList = async ()=>{
       const res =  await axios.get(URL_API)
       list.value = res.data.data.channels
    }
    return{
        price,
        increament,
        doubleCount,
        list,
        getList
    }
})

需要再src目录下新建一个store文件夹,在里面新建一个counter.js文件,如图所示的代码内容。

<script setup>
//1,导入useCounterStore 
import {useCounterStore} from './store/counter.js'
//2 执行方法得到实例对象
const counterStore = useCounterStore()

import { onMounted } from 'vue';
import { storeToRefs } from 'pinia'

//借助于pinia官方提供的函数,实现解构,就可以直接调用数据了。
const {price,doubleCount} = storeToRefs(counterStore)


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

<template>
    <h3>Pinia的基础练习</h3>
    <p>草莓单价:{
  { counterStore.price }}</p>
    <hr />
    <p>草莓单价乘以2={
  { counterStore.doubleCount }}</p>
    <button @click="counterStore.increament">草莓单价自增1</button>
    <hr/>
    <ul>
        <li v-for="item in counterStore.list" :key="item.id">{
  { item.name }}</li>
    </ul>
</template>

这个是入口文件的练习内容。可以看见,我们是使用了对象.属性,的方式较为传统。


如图,是可以正常拿到数据的。按钮也可以触发里面的方法。


//借助于pinia官方提供的函数,实现解构,就可以直接调用数据了。
const {price,doubleCount} = storeToRefs(counterStore)

这个就是解构函数的用法。很简单,我们不再演示代码了,大家可以自己试试。

有了它,就不需要对象了,直接可以拿到数据和方法。直接用就行了。

最近更新

  1. TCP协议是安全的吗?

    2024-01-23 12:34:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-23 12:34:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-23 12:34:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-23 12:34:01       20 阅读

热门阅读

  1. LED流水灯

    2024-01-23 12:34:01       23 阅读
  2. 智能小程序主题适配指南(各参数配置详情)

    2024-01-23 12:34:01       41 阅读
  3. 区块链当中Bitcoin的Segwit地址生成原理

    2024-01-23 12:34:01       40 阅读
  4. Spring Boot 指定外部配置文件

    2024-01-23 12:34:01       32 阅读
  5. 免费可用的ChatGPT替代方案

    2024-01-23 12:34:01       90 阅读
  6. 《幻兽帕鲁》服务器该如何选购

    2024-01-23 12:34:01       37 阅读
  7. 笔记-孙子兵法-第二篇-作战-就地补充,速战速决

    2024-01-23 12:34:01       32 阅读