zheng 6 days ago
parent
commit
0dc7f5055b
2 changed files with 57 additions and 5 deletions
  1. 25 2
      17.Vue3/project4/src/components/Count.vue
  2. 32 3
      17.Vue3/project4/src/store/count.ts

+ 25 - 2
17.Vue3/project4/src/components/Count.vue

@@ -1,20 +1,43 @@
 <template>
   <div>
     <h1>计数器</h1>
-    <h3>初始值:{{ count }}</h3>
+    <h3>初始值:{{ count }}--变大{{ bigCount }}</h3>
+    <h3>{{ hi }}--变大写{{ bigWord }}</h3>
+    <h3>
+      <input type="text">
+      <br>
+      <br>
+      <select>
+        <option value="10">10</option>
+        <option value="15">15</option>
+        <option value="20">20</option>
+      </select>
+    </h3>
+    <button>添加数值</button>
+    <button @click="handleAdd1">同步count+1</button>
+    <button @click="handleAdd2">异步count+2</button>
   </div>
 </template>
 
 <script lang="ts" setup>
 import {ref,computed} from "vue" 
+import { storeToRefs } from "pinia";
 import { useCountStore } from "@/store/count"; 
 const counter = useCountStore();
 console.log(counter);
-let {count} = counter;
+let {count,bigCount,hi,bigWord} = storeToRefs(counter);
 // let count = ref(5);
 // let bigCount = computed(()=>{
 //     return count.value * 3;
 // })
+function handleAdd1() {
+  console.log("同步count+1");
+  counter.addCount();
+}
+function handleAdd2() {
+  console.log("异步count+1");
+  counter.asyncAddCount();
+}
 </script>
 
 <style lang="scss" scoped>

+ 32 - 3
17.Vue3/project4/src/store/count.ts

@@ -1,13 +1,42 @@
 // 用于创建Store
-import {defineStore} from 'pinia';
+import { defineStore } from 'pinia';
 
 
 // 定义Store并抛出
-export const useCountStore = defineStore('count1',{
+export const useCountStore = defineStore('count1', {
     // 1.存储数据 类似于data
     state() {
         return {
-            count: 666
+            count: 666,
+            hi: 'hello piniaa'
+        }
+    },
+    // 2.计算属性 computed
+    getters: {
+        bigCount: (state) => state.count * 3,
+        // bigWord:(state) => {return state.hi.toUpperCase()}
+        bigWord() {
+            return this.hi.toUpperCase()
+        }
+    },
+    // 方法 methods
+    actions: {
+        // 同步
+        addCount() {
+            this.count++;
+        },
+        addCount1() {
+            console.log("addCount1")
+            this.count += 2;
+        },
+        // 异步
+        async asyncAddCount() {
+            console.log("执行")
+            // await new Promise((reslove)=>setTimeout(reslove,1000));
+            // this.addCount()
+            await new Promise((reslove)=>setTimeout(reslove,1000));
+            this.addCount1()
+            console.log("结束",this.count);
         }
     }
 });