0

I'm writing a plug-in based on Vue 3, and now I need a feature that is obviously not part of the Vue 3 API, and I think that requires some knowledge of the Vue 3 source code to do that, here is a description of the required functionality:

Suppose you have the following code snippet:

<div class="box">
    <input type="text" v-model="state.text">
</div>

<script>
    const {createApp, reactive} = Vue
    const vm = createApp({
        setup ()
        {
            const state = reactive({
                text: "123"
            })

            return {
                state
            }
        }
    }).mount(".box")
</script>

Based on this code snippet, I need to modify the v-model value outside of Vue through the dom object of the input element. How can I do this?

const input_dom = document.querySelector("input")

// I have obtained the input_dom, and I hope to change the value of state.text through input_dom.

input_dom??
4
  • you have to use pinia or vuex to store the data in state. On update the value you also need to update the state. check here vuex.vuejs.org/guide/state.html Commented Oct 30, 2023 at 9:51
  • @sandipbharadva This seems irrelevant to the question Commented Oct 30, 2023 at 10:03
  • please check this : stackoverflow.com/questions/47281746/… Commented Oct 30, 2023 at 10:08
  • This is XY problem, consider reasking the question and explaining the actual case. Vue doesn't do that. There may be internal properties like element.__vnode but they aren't documented and may not be supported in prod. If you have a demand to interact with the outside world, Vue app should have public api to support that, or possibly stick to web components instead of monolith app Commented Oct 30, 2023 at 12:33

1 Answer 1

0

There are undocumented __vue_app__, etc properties in Vue 3 but they are intended for debugging and may not be available in production build.

A good practice is to explicitly expose public API. If changing field value is expected, doing this with a method would be easier to debug and maintain.

document.querySelectorAll(".box").forEach(el => {
  const app = createApp({
    setup (props, ctx) {
      ...
      ctx.expose({
        update(val) {
          state.text = val;
        }
      });
    }
  });
  el.myApp = app.mount(el);
});

And used like:

document.querySelector(".box").myApp.change(...);

For single app instance it can be global variable as it's easier to track and debug:

window.myApp = app.mount("#box")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.