The most straightforward approach is to integrate Vuex
into your Vue 3 application and pass data through the Vuex store.
If you want to create a basic Vue 3 project using vue-cli, you can run the 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))...
}
}
Additionally, here is the entry point in src/main.js
.
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;
// Alternatively, you can also expose the store directly
// window.store = store;
- Expose the Vue app instance (window.vueApp) for external JavaScript access.
You can access the Vuex store like this.
// external.js
const store = window.vueApp.config.globalProperties.$store
/*
* You can manipulate data in the Vue app through `store`
*/
Demo
A predefined array is stored in the Vuex store as shown below:
// 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: {},
});
- The array
nums
needs to be displayed in App.vue
You can access the array nums
from the 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
represents the array of [0, 1, 2]
- List items are rendered with values (0, 1, 2)
The array nums
can be updated externally using the following script:
// external.js
const store = window.vueApp.config.globalProperties.$store
store.commit('replaceNum', [2, 3, 5, 7, 11]);
commit('replaceNum', ...)
- This triggers the replaceNum
method in mutations, updating the nums
array and refreshing the contents as well.