Vue 3 SFC – Too Colline Jul 13 '22 at 07:39

2 Answers2

1

I looked solution in this way, so God is got me a good point, which I met here https://phphe.com/article/frontend/vue3-meta-simple-solution

So you could use composable object. Like this

//validation.ts

const hasError = refs(false);

function useValidation(value: any, vm: ComponentInternalInstance) {

  onMounted(() => { 
      /* ... do some stuff here for validation value */
     hasErrors.value = /* checkValue if it's valid /*
  }, vm)

 return {
  hasErrors
 }
}
export { 
  useValidation
}

then using it, like this:

// component.vue

import { useValidation } from './Validation.ts'

const text = ref('');
const vm = getCurrentInstance();
const { hasErrors } = useValidation(text, vm);

here onMounted has two parameters, first is a hook, and second is a instance of component that has context.

export declare const onMounted: (hook: () => any, target?: ComponentInternalInstance | null) => false | Function | undefined;

Also vue3 api docs has clarification about what is instance of the component:

https://dtinth.github.io/api-documenter-yaml-to-antora-asciidoc/vue3-apidocs-example/api/vue_runtime-core_ComponentInternalInstance_interface.html

And they said that

We expose a subset of properties on the internal instance as they are useful for advanced external libraries and tools.

Which you could get via method getCurrentInstance()

0

When using <script setup>, you can access props with:

const props = defineProps({
  myProp: {
    type: String,
    required: true,
    default: "test"
  },
  // other props
});

console.log(props.myProp)

And emits with:

const emit = defineEmits(["myEmit", "anotherCustomEvent", "..."]);
const someData = "test";

emit("myEmit");
emit("myEmit", someData);

More from the official docs

Nicola Spadari
  • 549
  • 3
  • 10
  • This is fine, but what about the root instance? – Too Colline Jul 12 '22 at 14:11
  • 1
    Maybe related to this question? https://stackoverflow.com/questions/61600078/vue-3-composition-api-how-to-get-the-component-element-el-on-which-componen – Nicola Spadari Jul 12 '22 at 14:29
  • 1
    I think that's mostly about template refs and I'm mostly asking about getting the root instance of a component using the ` – Too Colline Jul 12 '22 at 14:37