pinia សម្រាប់ vue គឺជាផ្ទុកទិន្ន័យនៃ page បណ្តោះអាសន្ន (Keeps track of application ) វាមានភាពងាយស្រួលក្នុងការចូល page នីមួួយៗរួចហើយយើងត្រឡបក្រោយវីញដោយទិន្ន័យមិនបាត់
មុននឹងយើងទៅសិក្សាអំពីវា យើងមកមើលប្រើ Vue components ធម្មតាសិន។ ដោយយើងប្រើមួយលេខ
<template> <div> <div class="num"> {{ number }} </div> <div class="btn"> <button @click="decreaseNum">-</button> <button @click="increaseNum">+</button> </div> </div> </template> <script setup> import {ref} from 'vue' const number = ref(0) const increaseNum = ()=>{ number.value ++ }; const decreaseNum = ()=>{ number.value -- } </script>
computed
<template> <div> <div class="num"> {{ number }} </div> <div class="btn"> <button @click="decreaseNum">-</button> <button @click="increaseNum">+</button> </div> <h1>{{ oddEven }}</h1> </div> </template> <script setup> import {ref, computed} from 'vue' const number = ref(0) const increaseNum = ()=>{ number.value ++ }; const decreaseNum = ()=>{ number.value -- } const oddEven = computed(()=>{ if (number.value % 2 == 0) return 'odd' return 'Even' }) </script> <style scoped> .num{ font-size: 3em; } .btn button{ padding: 10px; font-size: 2em; } </style>
យើងបានអនុវត្តន៍មេរៀននេះរួចមកហើយ ទាំងអស់នេះយើងបានធ្វើនៅ home page ផ្ទុយទៅវិញប្រសិនជាយើងចុចលើ page About រួចហើយចុច home page វិញនោះទិន្ន័យវាលូតមកដើមវីញ។ ដើម្បីកុំឲ្យវាលូតនោះយើងត្រូវប្រើ pinia
Pinia
នៅពេលដំឡើង project យើងត្រូវជ្រើសរើសយក yes នៃ Add Pinia for state management
ដើម្បី edit នោះយើងត្រូវចូលទៅក្នុង folder stores ហើយ file counter.js
នៅក្នុង pinia វាមានបីគឺ៖ state, actions និង getters
សិក្សា state:
state: ()=>({})
File counter.js
File HomeView.vue
<template> <div> <div class="num"> {{ numStore.count }} </div> <div class="btn"> <button>-</button> <button>+</button> </div> </div> </template> <script setup> import {useCounterStore} from '@/stores/counter' const numStore = useCounterStore() </script>
សិក្សា action:
actions: {}
សិក្សា getters:
getters: {}
import { ref, computed } from 'vue' import { defineStore } from 'pinia' export const useCounterStore = defineStore({ id: 'count', state: ()=>({ count: 0 }), actions: { increase(){ this.count++ }, decrease(){ this.count-- } }, getters: { oddEven:(num)=>{ // Logic to find and return item based on num if(num.count % 2 == 0) return 'Odd' return 'Even' } } })
<template> <div> <div class="num"> {{ numStore.count }} </div> <div class="btn"> <button @click="numStore.decrease">-</button> <button @click="numStore.increase">+</button> </div> </div> <h1>{{ numStore.oddEven }}</h1> </template> <script setup> import {useCounterStore} from '@/stores/counter' const numStore = useCounterStore() </script> <style scoped> .num{ font-size: 3em; } .btn button{ padding: 10px; font-size: 2em; } </style>
Two way data blinding
ប្រើទិន្ន័យ Everywhere
នៅ page About ចង់បង្ហាញទិន្នទន្ន័យលេខដូចគ្នា
0 Comments