How to get set in composition api for step form?

Viewed 6787

I am trying to create a multi step form with composition api. In vue 2 I used to do it this way

    email: {
                get() {
                    return this.$store.state.email
                },
                set(value) {
                    this.$store.commit("setEmail", value)
                }
            },

Now I have my own store, I made this computed property to pass to my component stEmail: computed(() => state.email). How can I actually use this in get set?

I am trying do something like this but completely doesn't work.


  let setMail = computed(({
    get() {
      return stEmail;
    },
    set(val) {
      stEmail.value = val;
    }
  }))
const state = reactive({
  email: "",
})


export function useGlobal() {

  return {
    ...toRefs(state),
    number,
  }
}

Or is there better way now to make multi step forms?

2 Answers

You can do the same with the Composition API. Import useStore from the vuex package and computed from vue:

import { computed } from 'vue';
import { useStore } from 'vuex';

And then use it in your setup() function like this:

setup: () => {
  const store = useStore();

  const email = computed(() => ({
    get() {
      return store.state.email;
    },
    set(value) {
      store.commit("setEmail", value);
    }
  });

  return { email };
}

If you want to avoid using vuex, you can just define variables with ref() and export them in a regular JavaScript file. This would make your state reusable in multiple files.

state.js

export const email = ref('initial@value');

Form1.vue/Form2.vue

<template>
  <input v-model="email" />
</template>

<script>
import { email } from './state';

export default {
  setup() {
    return { email };
  }
};
</script>

As Gregor pointed out, the accepted answer included an anonymous function that doesn't seem to work, but it will work if you just get rid of that part. Here's an example using <script setup> SFC

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()

const email = computed({
    get() {
      return store.state.email
    },
    set(value) {
      store.commit("setEmail", value)
    }
})
</script>

<template>
    <input type="email" v-model="email" />
</template>
Related