欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3?pinia管理數(shù)據(jù)的3種方式代碼

 更新時(shí)間:2024年04月10日 09:22:48   作者:小饅頭學(xué)python  
在Vue3中Pinia是一個(gè)狀態(tài)管理庫,它提供了一種簡單而強(qiáng)大的方式來管理應(yīng)用程序的狀態(tài),這篇文章主要給大家介紹了關(guān)于Vue3?pinia管理數(shù)據(jù)的3種方式,需要的朋友可以參考下

第一種

我們首先將需要的代碼文件呈現(xiàn)一下

<template>
<div class="count">
    <h2>當(dāng)前求和為:{{ countStore.sum }}</h2>
    <h3>歡迎來到:{{ countStore.school }},坐落于:{{ countStore.address }}</h3>
<select v-model.number="n">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
    <button @click="_add">加</button>
    <button @click="_jian">減</button>
</div>
</template>
<script setup lang='ts' name="Count">
    import {ref} from 'vue'
    import {useCountStore} from '@/store/Count'
    const countStore = useCountStore()
    let n = ref(1)

    function _add(){
  
    function _jian(){
        
    }

</script>
<style scoped>
  .count {
    background-color: skyblue;
    padding: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px;
  }
  select,button {
    margin: 0 5px;
    height: 25px;
  }
</style>

還有Count.ts

import {defineStore} from 'pinia'

export const useCountStore = defineStore('Count',{
  // 真正存儲(chǔ)數(shù)據(jù)的地方
  state(){
    return {
      sum:2,
      school:'北京大學(xué)',
      address:'北京'
    }
  }
})

第一種修改方式屬于拿到就可以修改

countStore.sum+=n.value

第二種

第二種修改方式是,適用場景是很多數(shù)據(jù)需要同時(shí)的變更

countStore.$patch({
          sum:888,
          school:'清華大學(xué)',
          address:'北京'
        }) 

第三種

第三種方法是使用action

在Count.ts中將action寫好

actions:{
    increment(value){
      if( this.sum < 10){
        // 修改數(shù)據(jù)(this是當(dāng)前的store)
        this.sum += value
      }
    }
  }

再回到Count.vue加一行

countStore.increment(n.value)

這樣就可以修改了

附:vue代碼里監(jiān)聽 pinia的某個(gè)屬性

我們可以使用 watch 函數(shù)或 watchEffect 函數(shù)來監(jiān)聽 pinia的變化。

使用 watch 函數(shù)來監(jiān)聽 pinia 的變化:

<template> 
  <div> 
   Count: {{ pinia.count }}
    <button @click="pinia.addCount"></button>
  </div> 
</template>
 <script setup>
import { watch } from 'vue'
<code>import { myPinia} from './pinia' 
const pinia = myPinia()
  watch(() => pinia .count, (newVal, oldVal) => {
      console.log(`count changed from ${oldVal} to ${newVal}`)
    })</code>
<code></script> </code> 

總結(jié)

以上就是在Vue3中使用Pinia管理數(shù)據(jù)的三種方式

到此這篇關(guān)于Vue3 pinia管理數(shù)據(jù)的3種方式的文章就介紹到這了,更多相關(guān)Vue3 pinia管理數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論