vue-use-utilities icon indicating copy to clipboard operation
vue-use-utilities copied to clipboard

How to use ...useState within <script setup> ?

Open Fenrir200678 opened this issue 2 years ago • 1 comments

Hi, I'm currently playing around with the vuex composition helpers. It works fine if you use it in the setup method like in the docs:

import { useVuex } from '@vueblocks/vue-use-vuex'

export default {
  setup () {
    const { useState } = useVuex()

    return {
      ...useState({
        count: state => state.count,
      })
    }
  }
}

But how can we get it to work within

<script setup>
import { useVuex } from '@vueblocks/vue-use-vuex'

const { useState } = useVuex()
...useState({    // Won't work
  count: state => state.count
})
</script>

I tried to assign it to a variable like so

const { useState } = useVuex()
const store = {
  ...useState({
    count: state => state.count
  })
}
const { count } = store

But that throws an Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'state'). What am I missing?

Fenrir200678 avatar Oct 07 '22 08:10 Fenrir200678

image

import {mapState, useStore} from "vuex";
import {computed} from "vue";

export default function useState(mapper) {
    const store = useStore()
    const stateFnsObj = mapState(mapper)
    const newState = {}
    Object.keys(stateFnsObj).forEach(key => {
        newState[key] = computed(stateFnsObj[key].bind({$store: store}))
    })
    
    return newState
}

import {mapGetters, useStore} from "vuex";
import {computed} from "vue";

export default function useGetters(mapper) {
    const store = useStore()
    const gettersFnsObj = mapGetters(mapper)
    const newGetters = {}
    console.log('@', gettersFnsObj)
    Object.keys(gettersFnsObj).forEach(key => {
        newGetters[key] = computed(gettersFnsObj[key].bind({$store: store}))
    })
    
    return newGetters
}

<template>
  <div class="app">
    <h2>App 组件,当前计数为:{{ count }}</h2>
    <h2>App 组件,名字:{{ name }}</h2>
    <h2>App 组件,年龄:{{ age }}</h2>
    <Home/>
  </div>
</template>

<script setup>
import {computed} from "vue";
import {useStore} from "vuex";
import Home from "@/components/Home.vue";
import useState from "@/hooks/useState";

const store = useStore()

const count = computed(() => {
  return store.state.count
})

const {name, age} = useState(["name", "age"]);
</script>

<style lang="less">
.app {
  background-color: pink;
}
</style>

<template>
  <div class="home">
    <h2>Home组件</h2>
    <h2>当前 2 倍计数:{{ doubleCount }}</h2>
    <button @click="handleClick">点我+1</button>
  </div>
</template>

<script setup>

import {useStore} from "vuex";
import useGetters from "@/hooks/useGetters";

const store = useStore()
const handleClick = () => {
  store.commit("increment")
}
const {doubleCount} = useGetters(["doubleCount"])

</script>

<style lang="less" scoped>
.home {
  background-color: skyblue;
}
</style>

Aurorxa avatar Oct 20 '23 06:10 Aurorxa