如何在 <script setup> vue SFC 中访问 "this" 关键字
How to access "this" keyword in <script setup> vue SFC
我正在使用 typescript 为 vite、vue 和 vuetify 开发一个简单的脚手架,我想使用 SFC vue 的脚本设置版本
<script setup lang="ts">
我无法弄清楚的一件事是如何访问“this”关键字属性?
例如在我的旧 vue 项目中我可以这样写
this.$vuetify.themes.light.colors.primary
所以我能够在组件中的任何地方访问 $vuetify,但现在在脚本设置模式下“this”关键字未定义;
如何访问“这个”属性?
script
标签中的 setup
关键字是语法糖:
const myComponent = createComponent({
setup() {
const foo = "may-the-force";
let bar = "be-with-you";
return {
foo,
bar
}
}
})
所以自然地,在 setup
函数中,您不需要 this
关键字,因为现在您可以这样做:
bar = "be-not-with-you";
return {
foo,
bar
}
现在,当您启动 Vuetify 框架时,一个实例将保存在某个地方。像这样:
import Vue from "vue";
import { createVuetify } from 'vuetify'
Vue.use(Vuetify);
export const vuetify = createVuetify({ theme: {} });
现在您已经将 vuetify
实例存储在某个地方,您可以像导入任何其他 javascript/typescript 文件一样导入它:
<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>
编辑
我猜 Vue 3 中的情况有点不同。稍微研究一下后,您可以使用 getCurrentInstance
获取当前的 Vue 实例
<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>
我正在使用 typescript 为 vite、vue 和 vuetify 开发一个简单的脚手架,我想使用 SFC vue 的脚本设置版本
<script setup lang="ts">
我无法弄清楚的一件事是如何访问“this”关键字属性?
例如在我的旧 vue 项目中我可以这样写
this.$vuetify.themes.light.colors.primary
所以我能够在组件中的任何地方访问 $vuetify,但现在在脚本设置模式下“this”关键字未定义; 如何访问“这个”属性?
script
标签中的 setup
关键字是语法糖:
const myComponent = createComponent({
setup() {
const foo = "may-the-force";
let bar = "be-with-you";
return {
foo,
bar
}
}
})
所以自然地,在 setup
函数中,您不需要 this
关键字,因为现在您可以这样做:
bar = "be-not-with-you";
return {
foo,
bar
}
现在,当您启动 Vuetify 框架时,一个实例将保存在某个地方。像这样:
import Vue from "vue";
import { createVuetify } from 'vuetify'
Vue.use(Vuetify);
export const vuetify = createVuetify({ theme: {} });
现在您已经将 vuetify
实例存储在某个地方,您可以像导入任何其他 javascript/typescript 文件一样导入它:
<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>
编辑
我猜 Vue 3 中的情况有点不同。稍微研究一下后,您可以使用 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>