10-pinia

使用前需要先安装

npm install pinia

// state、getter 和 action,我们可以假设这些概念相当于组件中的 data、 computed 和 methods
// data可以通过this去调用
// computed就是计算属性,也能从中直接调用data的内容

使用步骤

  1. 在src下面新建文件夹,比如store,然后在文件夹下面新建一个js文件,比如counter.js
  2. 在counter.js中写入代码
  3. 在main.js中使用插件
  4. 在组件中操作数据

常规写法

import { defineStore } from "pinia"

// 注意:这里的名称 counter 建议和你的js文件名称保持一致
export const useCounterStore =  defineStore("counter",  {
    // 定义变量
    state: () => {
        return {count: 0, name: "小满"}
    },

    // 这里写方法,与后端交互的逻辑可以写在这里。
    actions: {
        increment(num){
            console.log(num);
            // 与后端交互,才真正的把数量增加
            this.count++
        },
        changeName(){
            this.name = '大乔'
        }
    },
    // 获取数据
    getters: {
        // 这个函数是自己定义的,就相当于计算属性
        // 计算属性必须返回
        // 视图调用的时候,不需要写括号 {{counter.getCounter}}
        getCount(){
            return this.count * 2
        }
    }
})
// main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router"

// 忽略掉无关的
import { createPinia } from 'pinia'
const pinia = createPinia() 
createApp(App).use(router).use(pinia).mount('#app')
<template>
  {{counter.count}}  -- {{counter.name}}  -- {{counter.getCount}} 
  <hr>
  <ul v-for="(item, index) in carArr" :key=item.id>
    <li>编号{{index + 1}} : 名称:{{item.name}}  价格: {{item.price}}  <button @click="joinCar(item.id)">加入购物车</button></li>
  </ul>
  <button @click="counter.changeName()">修改名称</button>
</template>

<script setup>
    import { reactive } from "vue";
    import {useCounterStore} from "../store/counter.js"
    
    // 以后通过counter对象 操作其中state getter action的东西
    const counter = useCounterStore()

    const carArr = reactive([
        {id:1, name: "抱枕", price: 33},
        {id:2, name: "香水", price: 79},
        {id:3, name: "茶叶", price: 199}
    ])

    function joinCar(num){
        counter.increment(num)
    }

</script>

更优雅的写法

只重写store/counter.js

import { defineStore } from "pinia"
import { ref } from "vue";


export const useCounterStore =  defineStore("counter",  () => {
    let count = ref(0)
    let name = ref("小满")

    function increment(){
        count.value++
    }
    function changeName(){
        name.value = '大乔'
    }
    function getCount(){
        return count.value * 2
    }

    return {count, name, increment, changeName, getCount}
})

https://juejin.cn/post/7057439040911441957?searchId=20240508183338AAF7DE2E0714BA25F418

本文作者:小满三岁啦

本文链接:https://www.cnblogs.com/ccsvip/p/18180919

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   小满三岁啦  阅读(7)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑
  1. 1 夜空中最亮的星 小果酱
夜空中最亮的星 - 小果酱
00:00 / 00:00
An audio error has occurred.