'Vue CDN Script use state accross routes
Im using vue via CDN Script like this:
const Home = {
'template': `<h1>[[ $store.state.count ]]</h2>`,
}
const routes = [
{
path: '/',
name: 'home',
component: Home
},
...
]
const vuex_store = new Vuex.Store({
state: {
count: 45,
}
...
})
...
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes,
})
const app = Vue.createApp({
compilerOptions: {
delimiters: ["[[", "]]"]
},
store: vuex_store,
data(){ return {}}
...
})
app.use(router)
app.mount('#app')
But I cant access either the data() or $state in routes except only the page the script is on.
I'm not using npm or any package manager, and due to certain constraints I'm stuck with this method.
How can I make this work? HAVE THE STATE/DATA SHARED ON ALL ROUTE TEMPLATES.
Solution 1:[1]
the delimiters is not a global option so you must define it in every component you have
inside your createApp options saw the property store it's not the correct syntax for version 3 of Vue.js you should use it like your router with app.use() syntax
for the final thing, you should use <router-view></router-view> in your HTML to render the output (i guess you used but anyway)
you can see a working example of your question in the below snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>use vuex in cdn way</title>
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<script src="https://unpkg.com/vuex@4"></script>
<script>
const Home = {
compilerOptions: {
delimiters: ["[[", "]]"],
},
template: `<h1>[[ $store.state.count ]]</h1>`,
};
const routes = [
{
path: "/",
name: "home",
component: Home,
},
];
const vuex_store = new Vuex.Store({
state: {
count: 45,
},
});
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes,
});
const app = Vue.createApp({});
app.use(router);
app.use(vuex_store);
app.mount("#app");
</script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad Masoudi |
