javascript - Vue 3 组合 API 和对 Vue 实例的访问

标签 javascript vue.js vue-component vuejs3 vue-composition-api

main.js我有这样的事情:

import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });

这样我就可以访问 myUtilFunc在整个应用程序中使用 this.$myUtilFunc
但是我怎样才能在 setup() 中达到同样的效果? Vue 3 中的方法,如果我无权访问 this ?

最佳答案

使用provide/inject 提供

const app = createApp(App);
app.provide('someVarName', someVar);  // `Provide` a variable to all components here
注入(inject) :
// In *any* component
const { inject } = Vue;
...
setup() {
  const someVar = inject('someVarName');   // injecting variable in setup
}
请注意,您不必从应用根目录提供,也可以 provide从任何组件到仅其子组件:
// In *any* component
setup() {
  ...
},
provide() {
  return {
    someVarName: someVar
  }
}

原始答案
[ 编辑 :虽然我下面的原始答案对 context 仍然有用属性,不再推荐使用context.rootguide 中不再提及并且可能很快就会被弃用。]
在 Vue 3 中,setup context 有一个可选的第二个参数.您可以通过 context.root 访问 Vue 实例而不是 this :
setup(props, context) {
  context.root.$myUtilFunc  // same as `this.$myUtilFunc` in Vue 2
}
您可以通过 context 访问的内容:
context.attrs
context.slots
context.parent
context.root
context.emit

关于javascript - Vue 3 组合 API 和对 Vue 实例的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60202724/

相关文章:

css - 是否可以将 css 注入(inject) Vue 组件样式部分?

javascript - 使用 v-for 时出现问题。带点的 Prop 不显示

javascript - 了解匿名函数的作用域和返回值

javascript - 如何使用 ctags 索引简单的 javascript 哈希/对象?

javascript - 如何避免由于 Ext Direct 和动态语言环境加载而导致的嵌套异步回调?

javascript - 如何访问另一个子组件中的插槽内容

javascript - 我的函数调用不起作用?

javascript - Vuetify 现有项目生成错误

javascript - 如何通过变量将方法名称传递给@click来绑定(bind)方法

vue.js - 在子组件之间传递数据