Vue3 Pinia獲取全局狀態(tài)變量的實現(xiàn)方式
使用說明
在 Pinia 中,獲取狀態(tài)變量的方式非常的簡單 : 就和使用對象一樣。
使用思路:
- 1、導(dǎo)入Store
- 2、聲明Store對象
- 3、使用對象
在邏輯代碼中使用
但是 Option Store
和 Setup Store
兩種方式定義的全局狀態(tài)變量在獲取的時候還是有簡單的區(qū)別
的:
Option Store
: 聲明Store對象之后,可以直接使用屬性,例如 : 【store.name】Setup Store
: 聲明Store對象之后,可以獲取到定義的聲明式對象,所以使用具體屬性時需要通過 該對象,例如 : 【store.student.name】
在html模板中使用
此處非常的簡單,Store對象中有一個$state
屬性,這個屬性就是我們定義的全局狀態(tài)變量。
下面通過具體的案例體會一下。
具體案例
本案例 有一個全局狀態(tài)變量的 配置文件,分別通過 Option Store
和 Setup Store
兩種方式定義了兩個全局狀態(tài)變量;
在組件A 中 導(dǎo)入兩個全局狀態(tài)變量,并分別在控制臺 和 頁面模板中讀取展示一下;
在 App.vue 文件中 存在 <router-view>
標簽用于組件的路由。
全局狀態(tài)變量配置文件
// 導(dǎo)入 defineStore API import { defineStore } from 'pinia' // 導(dǎo)入 reactive 依賴 import { reactive } from 'vue' // 定義全局狀態(tài)方式一 : option store export const useClassStore = defineStore('classinfo',{ state: () => ({ name:'快樂籃球二班', studentNum:30 }) }) // 定義全局狀態(tài)方式二 : setup store export const useStudentStore = defineStore('studentinfo',() => { // 響應(yīng)式狀態(tài) : student 是響應(yīng)式對象 const student = reactive({ name : '小明', age:12, className:'快樂足球一班' }) return { student } })
App.vue 組件
<template> <div class="basediv"> APP.vue 中的 msg : {{ msg }} <br> <br> <!-- 組件放在這里 --> <router-view></router-view> </div> </template> <script setup lang="ts"> // 引入 provide 方法 import { ref } from 'vue' // 聲明父組件的一個變量 const msg = ref('這是App根組件的msg變量') </script> <style scoped> .basediv{ width: 600px; height: 400px; border: 1px solid red; } </style>
組件A的代碼
<template> <div class="diva"> 這是組件A <br> <br> <!-- 使用 $state 來讀取全局狀態(tài)變量 --> classStore : {{ classStore.$state }} <br> studentStore : {{ studentStore.$state }} </div> </template> <script setup lang="ts"> // 導(dǎo)入全局狀態(tài)變量的定義 import { useClassStore,useStudentStore } from './storea' // 獲取全局狀態(tài)變量的對象 const classStore = useClassStore() const studentStore = useStudentStore() // 讀取一下全局的變量 console.log('組件A 中 : ',classStore) console.log('組件A 中 : ',studentStore) // Option Store 的方式 : 直接可以獲取到屬性 console.log('組件A 中 classinfo 對象 : ',classStore.name+' - '+classStore.studentNum) // Setup Store 的方式 : 仍然需要通過 定義的 student 對象,因為這個student 是真正的全局狀態(tài)對象 console.log('組件A 中 studentinfo 數(shù)據(jù)對象: ',studentStore.student.name+'-'+studentStore.student.age+'-'+studentStore.student.className) console.log('------') </script> <style scoped> .diva{ width: 450px; height: 250px; background: red; } </style>
運行結(jié)果
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue實現(xiàn)播放后端flask發(fā)送的mp3文件
這篇文章主要為大家詳細介紹了vue如何實現(xiàn)播放后端flask發(fā)送的mp3文件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習一下2024-01-01關(guān)于Vue3中element-plus的el-dialog對話框無法顯示的問題及解決方法
最近今天在寫一個停車場管理系統(tǒng)的項目時,在用vue3寫前端時,在前端模板選擇上,我一時腦抽,突然決定放棄SpringBoot,選擇了以前幾乎很少用的element-plus,然后果不其然,錯誤連連,下面給大家分享dialog對話框無法顯示的原因,感興趣的朋友一起看看吧2023-10-10關(guān)于Vue新搭檔TypeScript快速入門實踐
這篇文章主要介紹了關(guān)于Vue新搭檔TypeScript快速入門實踐,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09