search

Home  >  Q&A  >  body text

Unable to get Vuex's getters etc. to work properly with Vue3's <script setup> composition API

If I use the composition API in Vue 3 and use the regular setup() method like below, I can get it to work:

<script>
  import { useStore } from 'vuex'
  import { computed } from 'vue'

  export default {
    const store = useStore()

    setup () {
      const loginStatus = computed(() => store.getters.loginStatus)

      return { loginStatus }
    }
  }
</script>

loginStatus is now available in templates and can be used in html.

But when I try to use the newer <script setup> syntax, the const is no longer captured and exposed to the template.

I shouldn't be returning anything from the script setup, but it doesn't happen automatically either. Eslint marks loginStatus as unused. I can't find any information on how to use Vuex in this context:

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

  const loginStatus = computed(() => store.getters.loginStatus)
</script>

Is this expectation that will not work? Or do you know of a recommended approach?

Edit 1:

I'm aware of this answer where the accepted solution is not the recommended composition API syntax, the second answer involves writing boilerplate code of my own creation that makes what I want to do possible, but doesn't seem to be the official way (if there is one if).

Edit 2:

As the commenters pointed out, my code actually works. However, I was fooled by the Vetur extension marking variables as not returned. So in the template it looks like to me that's why it's not being captured. In fact, an unrelated error is the real cause.

Because of this Vetur problem, I still use the old setup syntax for the time being.

P粉903969231P粉903969231241 days ago423

reply all(2)I'll reply

  • P粉842215006

    P粉8422150062024-03-26 14:39:27

    I’ve been trying

    import { computed } from 'vue';
    import { useStore } from 'vuex';
    
    const store = useStore();
    
    const con = computed(() => store.getters.connected);

    In this case connected is just a boolean, but I've also tried using an object and it still works.

    My template:

    <template>
      <h1>{{ con }}</h1>
    </template>

    It works fine.

    reply
    0
  • P粉446800329

    P粉4468003292024-03-26 11:14:59

    Your usage in <script setup> is actually valid, but as pointed out in the comments, Vetur VS Code extension shows misleading errors.

    Starting from version 0.34.1, Vetur does not support <script setup>. The recommended extension for <script setup> is Volar. This was even tweeted from Vue's official Twitter account yesterday:

    reply
    0
  • Cancelreply