My main problem is that I'm trying to reactively add data to either the Vue root or a Vue component. The reason this is an issue is because once my Vue app instance is mounted, (using app.mount()), I am unable to reactively add data to the Vue application. I am trying to use Vue along with vanilla JS as I am a novice with the framework. I guess what it really comes down to is... is there any event I could trigger or object I could call in vanilla JS to insert new data into lets say an array of objects within the Vue app instance?
Easiest way is to install Vuex into your vue 3 app and inject data through vuex store.
Here is simple, plain vue3 project generated from vue-cli with command vue create my-vue-prj
{
"name": "my-vue-prj",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
...((skipped))...
}
}
And src/main.js entry point.
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
const app = createApp(App);
app.use(store).mount("#app");
window.vueApp = app;
// or can expose store directly
// window.store = store;
Vuex store can be access like this.
// external.js
const store = window.vueApp.config.globalProperties.$store
/*
* can inject(modify, delete, etc) data into vue app through `store`
*/
An array is defined in vuex store like this
// file : src/store/index.js
import { createStore } from "vuex";
export default createStore({
state: {
nums: [0, 1, 2],
},
mutations: {
replaceNum(state, nums) {
state.nums = nums;
},
},
actions: {},
modules: {},
});
nums want to be render in App.vueArray nums can be accessed from component App.vue.
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<ul>
<li v-for="(n, index) in $store.state.nums" :key="index">{{ n }}</li>
</ul>
</template>
$store.state.nums is array of [0, 1, 2]Array nums can be updated from external js
// external.js
const store = window.vueApp.config.globalProperties.$store
store.commit('replaceNum', [2, 3, 5, 7, 11]);
commit('replaceNum', ...) - call method replaceNum in mutations. It updates nums and contents is also refreshed.