Home > Enterprise >  Vue 3 Mutate Composition API state from external script
Vue 3 Mutate Composition API state from external script

Time:08-18

Forewords

In Option API, I was able to directly mutate instance data properties without losing any of reactivity. As described in here.

If you ask why, well not everything is written in Vue and there're cases where external JS libraries have to change certain value inside Vue instance.

For example:

document.app = createApp({
    components: {
        MyComponent, //MyComponent is a Option API
    }
})


//Somewhere else

<MyComponent ref="foo"/>

Then component state can be mutated as follow:

//Console:
document.app.$refs.foo.$data.message = "Hello world"

With the help of ref, regardless of component hiarchy, the state mutating process is kept simple as that.

Question

Now in Composition API, I want to achieve the same thing, with setup script if it's possible.

When I do console.log(document.app.$refs), I just only get undefined as returned result.

So let's say I have MyComponent:

<template>
    {{message}}
<template>

<script setup>
    const message = ref('Hello world');
</script>

How to mutate this child component state from external script? And via a ref preferably, if it's easier

CodePudding user response:

Refs that are exposed from setup function are automatically unwrapped, so a ref can't be changed as a property on component instance.

In order for a ref to be exposed to the outside, this needs to be explicitly done:

setup(props, ctx) {
   const message = ref('Hello world');

   ctx.expose({ message });

   return { message };
}

This is different in case of script setup because variables are exposed on a template but not component instance. As the documentation states:

An exception here is that components using are private by default: a parent component referencing a child component using won't be able to access anything unless the child component chooses to expose a public interface using the defineExpose macro

It should be:

<script setup>
...
const message = ref('Hello world');
defineExpose({ message });
</script>
  • Related