Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

79
Views
How to access "this" keyword in <script setup> vue SFC

I am working on a simple scaffold for vite, vue and vuetify with typescript and I wanted to use the script setup version of SFC vue

<script setup lang="ts">

One thing that I can't figure out is how to access "this" keyword properties?

for example in my old vue projects i could write this

this.$vuetify.themes.light.colors.primary

so i had the ability to access $vuetify anywhere in the component, but now in script setup mode "this" keyword is undefined; How to access "this" properties?

5 months ago · Juan Pablo Isaza
1 answers
Answer question

0

The setup keyword in the script tag is a syntax sugar for:

const myComponent = createComponent({
  setup() {
    const foo = "may-the-force";
    let bar = "be-with-you";

    return {
      foo,
      bar
    }
  }
})

So naturally, in a setup function, you won't need this keyword because now you can just do:

bar = "be-not-with-you";

return {
  foo,
  bar
}

Now, when you initiated your Vuetify framework an instance is going to be kept somewhere. Something like this:

import Vue from "vue";
import { createVuetify } from 'vuetify'

Vue.use(Vuetify);

export const vuetify = createVuetify({ theme: {} });

Now that you have stored your vuetify instance somewhere you can import it just like you would do any other javascript/typescript file:

<script setup lang="ts">
import { vuetify } from "path/to/vuetify/instance";

console.log(vuetify.themes.light.colors.primary);

// You can even set dark mode if you prefer to
vuetify.framework.theme.dark = true;

</script>

Edit

I'm guessing that things are a little bit different in Vue 3. After researching a little bit you can get the current Vue instance by using getCurrentInstance

<script setup>
    import { getCurrentInstance } from 'vue'

    const app = getCurrentInstance()
    // it should be here in this instance the vuetify object with its properties
    console.log(app);
</script>
5 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs