vue3学习笔记—Pinia

本文介绍了如何安装和使用Pinia,展示了state、getters、actions的定义和使用方法,包括OptionStore和SetupStore两种模式。Pinia与Vuex相比,在类型推断、状态修改和模块化上有其独特之处,更适用于现代Vue项目,特别是TypeScript环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装Pinia

npm install pinia

定义Option Store

src\stores\index.js

import { defineStore } from 'pinia'

const useAgeStore = defineStore('AAAAA', {
  state:()=>{//data(){return{}} 防止数据污染
    return {age:30};
  },
  getters: {
    //相当于computed计算属性
    gettersAge(state){
      return state.age + 5 ;
    }
  },
  //vuex --->  actions(context,data){}
  actions: {
    //相当于methods
    addAge(){
      //this指向对应的store仓库 
      this.age++;
    },  
  }
})

 定义Setup Store

src\stores\index.js

import {computed,ref} from 'vue';

//Setup store
//setup(){return{}}
export const userCounterStore=defineStore('main',()=>{
  const counter=ref(30);//state
  const gettersCounter=computed(()=>{//getters
    return counter.value+5;
  })
  function addCounter(){//actions
    counter.value++;
  }
  return {counter,gettersCounter,addCounter}
})

src\views\HomeView.vue

<script setup>
import { useAgeStore, userCounterStore } from '../stores/index'
import { storeToRefs } from 'pinia';
const ageStore = useAgeStore();
const counterStore = userCounterStore();
// console.log(ageStore);
// console.log(counterStore);

const{counter,gettersCounter}=storeToRefs(counterStore);
const {addCounter} = counterStore;
</script>

<template>
  <main>
    <h2>{{ ageStore.age }}</h2>
    <h2>{{ ageStore.gettersAge }}</h2>
    <!-- vuex commit -->
    <button @click="ageStore.addAge">修改age值</button>

    <h2>{{ counter }}</h2>
    <h2>{{ gettersCounter }}</h2>
    <button @click="addCounter">修改counter值</button>
  </main>
</template>

state的基本使用

src\stores\index.js

import { defineStore } from 'pinia';

//Option Store
export const useAgeStore = defineStore('AAAAA', {
  state:()=>{
    //为了完整类型推理,推荐使用箭头函数  
    //在Pinia中,state被定义为一个返回初始状态的函数
    //这使得pinia可以同时支持服务端和客户端
    //data(){return{}} 防止数据污染(针对服务端)
    return {age:30,name:"张三",arr:[1,2,3,4]};
  },
  getters: {
    //相当于computed计算属性
    gettersAge(state){
      return state.age + 5 ;
    }
  },
  //vuex --->  actions(context,data){}
  actions: {
    //相当于methods
    addAge(){
      //this指向对应的store仓库 
      this.age++;
    },  
  }
});

src\viewsAboutView.vue

<script setup>
import { useAgeStore } from '../stores/index'
const ageStore = useAgeStore();
console.log(ageStore.age);
//修改state中的状态

function changeAge(){
//方式一,直接修改
// ageStore.age++;

//方式二,批量修改$patch(对象),建议使用
// ageStore.$patch({
//   age:40,
//   name:"张三丰",
//   arr:[...ageStore.arr,5]
// })

//方式三,批量修改$patch(函数),强烈推荐
//state-->store中定义的state
ageStore.$patch((state)=>{
  state.age=40;
  state.name="张三丰";
  state.arr.push(5);
})

//方式四,逻辑比较复杂的时候,封装到actions中的函数
}
</script>

<template>
  <main>
    <h2>{{ ageStore.name }}</h2>
    <h2>{{ ageStore.age }}</h2>
    <h2>{{ ageStore.arr }}</h2>

    <!-- <h2>{{ ageStore.gettersAge }}</h2> -->
    <!-- vuex commit -->

    <button @click="changeAge">修改age值</button>
    
    <!-- 使用actions中的函数 -->
    <!-- <button @click="ageStore.addAge">修改age值</button> -->
  </main>
</template>

getter的基本使用

src\stores\index.js

getters: {
    //相当于computed计算属性
    //state-->store中定义的state,推荐箭头函数
    // gettersAge(state){
    //   return state.age + 5 ;
    // },

    //this-->指向store实例,不能对返回值自动推导
    // gettersAge(){
    //   return this.age+5;
    // },

    //访问其他getters,通过this,不能使用箭头函数
    // gettersName(state){
    //   return this.gettersAge+state.name;
    // },

    //向getters传递参数,返回函数的方式接受参数,和普通函数一样
    //没有缓存作用
    // gettersAge(state){
    //   return (data)=>state.age + data ;
    // },

    //访问其他的store中的getters
    gettersAge(state){
      const counterStore=userCounterStore();
      return state.age+counterStore.gettersCounter;
    }
  },

src\viewsAboutView.vue 

<script setup>
import { useAgeStore } from '../stores/index'
const ageStore = useAgeStore();
</script>

<template>
  <main>
    <h2>{{ ageStore.gettersAge }}</h2>

    <!-- vuex commit -->
    <button @click="changeAge">修改age值</button>
  </main>
</template>

action的基本使用

src\stores\index.js

import axios from "axios"


  actions: {
    //既可以处理同步,也可以处理异步
    //不能使用箭头函数,一定要使用普通函数
    //相当于methods-->data
    addAge() {
      //this指向对应的store仓库 
      this.age++;
    },

    //访问其他store中的actions
    async getList() {
      const counterStore = userCounterStore();
      if (counterStore.login()) {
        let res = await axios.get('地址');
        console.log(res);
      }

    }
  }

src\viewsAboutView.vue 

<script setup>
import { useAgeStore } from '../stores/index'
const ageStore = useAgeStore();
console.log(ageStore.age);
//修改state中的状态

function getData(){
  ageStore.getList()
};
</script>

<template>
  <main>
    <button @click="getData">获取数据</button>
  </main>
</template>

pinia和vuex的比较

1.pinia最重要的是,搭配 TypeScript一起使用时有非常可靠的类型推断支持
2.pinia 没有 mutations,而actions的使用不同,在actions中可以处理同步也可以处理异步,getters的使用是一致的,state与vue2中data是相似的
3.pinia 没有总出口全是模块化,需要定义模块名称,当多个模块需要协作的时候需要引入多个模块,vuex是有总入口的,在使用模块化的时候不需要引入多个模块
4.pinia 在修改状态的时候不需要通过其他api,vuex需要通过commit,dispatch去修改所以在语法上比vuex更容易理解和使用,灵活
5.pinia就是更好的vuex,建议在项目中可以直接使用它了,尤其是使用了TypeScript的项目。

### Vue3 学习笔记 黑马程序员 Vue3Vue.js 的最新版本,带来了许多新特性和改进。以下是一份关于 Vue3 学习笔记的内容概述,结合了黑马程序员与尚硅谷联合整理的资料[^2],以及相关的学习资源[^1]。 #### 1. Vue3 核心概念 Vue3Vue2 的基础上进行了重大升级,引入了许多新的特性: - **Composition API**:一种新的组合逻辑的方式,替代了 Vue2 中的 Options API。 - **Teleport**:允许将组件的 DOM 结构渲染到应用的其他部分[^2]。 - **Fragments**:支持一个组件返回多个根节点。 - **更好的 TypeScript 支持**:Vue3 对 TypeScript 的支持更加友好,提供了更强大的类型推断能力。 #### 2. Vue3 基础特性 以下是 Vue3 的基础特性,适合初学者入门: - **模板语法**:包括 `v-text`、`v-html`、`v-on`、`v-show`、`v-if`、`v-bind`、`v-for` 和 `v-model` 等指令[^1]。 - **响应式系统**:Vue3 使用 Proxy 替代了 Vue2 中的 Object.defineProperty,性能更高且功能更强大[^2]。 #### 3. 组件化开发 Vue3 提供了更灵活的组件化开发方式: - **单文件组件 (SFC)**:通过 `.vue` 文件定义组件,包含模板、脚本和样式[^2]。 - **动态组件**:使用 `<component>` 和 `is` 属性实现动态组件切换[^2]。 #### 4. 状态管理 Vue3 推荐使用 Vuex 或 Pinia 进行状态管理: - **Vuex**:Vue 官方的状态管理库,适合中大型项目。 - **Pinia**:Vue3 的新一代状态管理工具,更轻量且易于使用。 #### 5. 路由应用 Vue Router 是 Vue.js 的官方路由管理器,适用于 Vue3 项目: - 配置路由规则。 - 实现页面跳转和参数传递。 - 处理导航守卫。 #### 6. 实战项目案例 学习 Vue3 不仅需要掌握理论知识,还需要通过实战项目巩固技能: - **计数器案例**:演示基本的事件绑定和数据绑定[^1]。 - **图片切换案例**:展示如何使用 `v-for` 和 `v-bind` 动态渲染列表[^1]。 - **小黑记事本**:综合运用 Vue3 的各种特性,如 `v-model`、`v-if` 和事件处理[^3]。 - **音乐播放器**:一个完整的综合应用案例,涉及网络请求、状态管理和组件通信。 #### 7. Vue2 到 Vue3 的迁移指南 对于从 Vue2 迁移到 Vue3 的开发者,官方提供了详细的迁移指南: - 了解 Vue3 的新特性。 - 更新项目依赖。 - 修改代码以适应 Vue3 的变化。 ### 示例代码 以下是一个简单的 Vue3 组件示例,展示了 Composition API 的用法: ```javascript <template> <div> <p>当前计数: {{ count }}</p> <button @click="increment">增加</button> </div> </template> <script> import { ref } from &#39;vue&#39;; export default { setup() { const count = ref(0); const increment = () => { count.value++; }; return { count, increment }; } }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值