vue.jsvuexvuejs3

Unable to make Vuex getters etc. work with <script setup> Vue3 composition API


I get this working in the Vue 3 with the composition API if I use the regular setup() method like so:

<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 exposed to the template and can be used in the html.

But when I try the newer <script setup> syntax the const isn't picked up and exposed to the template anymore.

I'm not supposed to return anything from script setup, but it doesn't happen automatically either. Eslint marks loginStatus as unused. I can't find any information about how Vuex is supposed to be used 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 expected not to work? Or do you know the recommended way of doing it?

EDIT 1:

I'm aware of this answer where the accepted solution isn't recommended composition API syntax and the second answer involves writing self-created boilerplate which makes what I want to do possible, but doesn't seem like the official way (if there is one).

EDIT 2:

As pointed out by commenters, my code actually did work. I was however fooled by the Vetur extension marking those unreturned variables as unused. So it looked to me like this was the reason it wasn't picked up in the template. In reality an unrelated error was the real reason.

Because of this Vetur issue I'll stick with the older setup syntax for now.


Solution

  • Your usage in <script setup> actually works, but as pointed out in comments, the Vetur VS Code extension was showing misleading errors.

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

    tweet