Search code examples
javascriptvue.jsvuejs3vue-composition-apivue-script-setup

Vue Script setup in build imports not accessible


My Problem is when I use setup I can't access it in normal script but only after I build the application in Dev mode anything works fine. In this example, I can't access this.authStore in my logout function.

`

<script setup>
import { ref } from "vue";
import { storeToRefs } from "pinia";
import { useAuthStore } from "@/stores/auth-store";
const authStore = useAuthStore();
const { user } = storeToRefs(authStore);

const searchDropdown = ref(false);
const showSearchDropdown = () => {
  searchDropdown.value = true;
};
const hideSearchDropdown = () => {
  searchDropdown.value = false;
};
</script>

<script>
export default {
  name: "Top Bar",
  data() {
    return {
      pageName: this.$route.name,
    };
  },
  methods: {
    async logout() {
      await this.authStore.logout();
    },
  },
};
</script>

`


Solution

  • Try to use only the composition API to make your code consistent, replace logout method by a function, use useRoute to get the route name :

    <script setup>
    import { ref } from "vue";
    import { usRoute } from 'vue-router'
    import { storeToRefs } from "pinia";
    import { useAuthStore } from "@/stores/auth-store";
    const authStore = useAuthStore();
    
    const { user } = storeToRefs(authStore);
    
    const searchDropdown = ref(false);
    
    const route = useRoute()
    const pageName=route.name
    const showSearchDropdown = () => {
      searchDropdown.value = true;
    };
    const hideSearchDropdown = () => {
      searchDropdown.value = false;
    };
    
    function logout(){
      authStore.logout();
    }
    </script>