gpt4 book ai didi

vue.js - 如何在 vue 3 中获取 this 实例?

转载 作者:行者123 更新时间:2023-12-02 16:14:58 33 4
gpt4 key购买 nike

在 vue 2+ 中,我可以很容易地得到 this 的实例,因此我可以写这样的东西,

// main.js
app.use(ElMessage)

// home.vue
this.$message({
showClose: true,
message: 'Success Message',
type: 'success',
})

我应该为 vue 3 做些什么,

Inside setup(), this won't be a reference to the current activeinstance Since setup() is called before other component options areresolved, this inside setup() will behave quite differently from thisin other options. This might cause confusions when using setup() alongother Options API. - vue 3 doc.

最佳答案

直接使用ElMessage

ElementPlus 支持以与 $message() 相同的方式使用 ElMessage,如 example 所示:

import { ElMessage } from 'element-plus'

export default {
setup() {
const open1 = () => {
ElMessage('this is a message.')
}
const open2 = () => {
ElMessage({
message: 'Congrats, this is a success message.',
type: 'success',
})
}

return {
open1,
open2,
}
}
}

使用$message()

Vue 3 在 setup() hook 中提供了 getCurrentInstance()(一个内部 API) .该实例允许通过 appContext.config.globalProperties 访问全局属性(从插件安装):

import { getCurrentInstance } from "vue";

export default {
setup() {
const globals = getCurrentInstance().appContext.config.globalProperties;
return {
sayHi() {
globals.$message({ message: "hello world" });
},
};
},
};

demo

注意:作为内部 API,getCurrentInstance() 可能会在未来的版本中被删除/重命名。谨慎使用。

关于vue.js - 如何在 vue 3 中获取 this 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66957578/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com