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>

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


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

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


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

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

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

01-26 23:05