Vue: pinia

 

 main.ts

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'


const store = createPinia()
const app = createApp(App)
app.use(store)
app.mount('#app')

store-namespace.ts

export const enum Names {
  test = 'TEST',
  vaunt = 'VAUNT'
}

index.ts

import { defineStore } from 'pinia'
import { Names } from './store-namespace'


type User = {
  name: string,
  age: number
}

const result: User = {
  name: 'pppp',
  age: 555
}

const Login = (): Promise<User> => {
  return new Promise<User>(resolve => {
    setTimeout(() => {
      resolve({
        name: 'resolved name',
        age: 5555
      })
    }, 2000)
  })
}
export const useVauntStore = defineStore(Names.vaunt, {
  state: () => {
    return {
      // current: 55,
      user: <User>{},
      name: 'rtyu'
    }
  },
  // computed
  getters: {
    newName(): string {
      return `$-${this.name}--${this.getUserAge}`
    },
    getUserAge(): number {
      return this.user.age || 66
    }
  },
  // methods
  actions: {
    // setCurrent() {
    //   this.current++
    // }
    setCurrent(n: number): void {
      // this.current = n
    },
    async setUser() {
      this.user = await Login()
      this.setName('uiop')
    },
    setName(name: string) {
      this.name = name
    }
  }
})

App.vue

<template>
  <div>
    <!--    pinia: {{ vassal.current }} &#45;&#45; {{ vassal.name }}-->
    <!--    <fieldset></fieldset>-->
    <!--    change:-->
    <!--    <button @click="change">change</button>-->
    <p>actions-user: {{ vassal.user }}</p>
    <hr>
    <p>actions-name: {{ vassal.name }}</p>
    <hr>
    <p>getters: {{ vassal.newName }}</p>
    <hr>
    <button @click="change">change</button>
    <p>
      <button @click="reset">reset</button>
    </p>
  </div>
</template>

<script lang="ts" setup>
import { useVauntStore } from './store'
import { storeToRefs } from 'pinia'


const vassal = useVauntStore()


/**
 * 1 vassal.current++ 直接操作
 * 2 vassal.$patch({current: 555, name: 'vassal'})
 * 3 vassal.$patch(state => {state.current++; state.name += '-B'})
 * 4 vassal.$state={current:555, name:'vassal'}
 * 5 vassal.setCurrent() 通过actions
 * 6 vassal.setCurrent(555)
 */

// const {current, name} = vassal  // not responsive
// const {current, name} = storeToRefs(vassal)  // responsive


// const change = () => {
//   console.log(vassal)
//   current.value++
//   name.value = 'vassal'
// }
vassal.$subscribe((args, state) => {
  console.log('----->', args)
  console.log('----->', state)
})

vassal.$onAction(args => {
  args.after(() => {
    console.log('after')
  })
  console.log('-------', args)

})

const change = () => {
  vassal.setUser()
  vassal.setName('yyyyyyyyy')
}

const reset = () => {
  vassal.$reset()
}

</script>

 

posted @ 2022-03-27 23:31  ascertain  阅读(80)  评论(0编辑  收藏  举报