[英]Vue 3 cdn example with vuex 4, but how do I access the store inside main.js?
我的應用程序結構:
> public
> scripts
> - cdn
> - vue.js
> - vuex.js
> main.js
> store.js
> index.html
在 head 標簽里面我有:
<script src="./scripts/cdn/vue.js"></script>
<script src="./scripts/cdn/vuex.js"></script>
<script src="./scripts/main.js" type="module"></script>
在我的身體里——
<div id="app"> <div v-for="item in items" >{{item.text}}</div> </div>
商店.js
console.log('test in store.js', store.state)
const store = new Vuex.createStore({
state: {
items: [{
text: 'ahhh STORE 1'
}, {
text: 'ahhh STORE 2'
}],
},
mutations: {
},
actions: {
test({
state
}) {
console.log(state.items)
}
},
modules: {
}
})
主程序
import * as store from "./store.js";
const {
onMounted,
onUpdated,
onUnmounted,
ref,
reactive,
getCurrentInstance
} = Vue; //here define only what you need
//Define Vue app
const App = {
state: store,
// store, //using either store or state: store does not work
data() {
return {};
},
methods: {},
setup(props, context) {
onMounted(() => {
console.info("App mounted!");
console.log('mounted state', store.state)
});
onUpdated(() => {
console.info("App updated!");
});
onUnmounted(() => {
console.info("App unmounted!");
});
}
};
// Create new Vue app
const app = Vue.createApp(App);
app.use(store)
app.mount("#app");
所以當應用程序運行時,它會在控制台中顯示
test in store.js Proxy { <target>: {…}, <handler>: {…} }
但是在onMounted
中它返回store.state
作為undefined
。 它可以通過在main.js
中使用createStore
來工作,但我想將其分開。
我缺少什么以及如何使主要商店可訪問?
app.use(store)
- 你已經將商店添加到 vue 實例中。
然后你可以從任何組件訪問這個存儲,例如使用:
import { mapState} from 'vuex';
...
computed: {
...mapState({
items: state => state.items
}),
},
或在setup
中:
import { useStore } from 'vuex';
...
setup(){
const store = useStore();
const state = store.state; // <-- state from vuex
}
您的工作示例:
const store = new Vuex.createStore({ state: { items: [{ text: 'ahhh STORE 1' }, { text: 'ahhh STORE 2' }], }, mutations: { }, actions: { test({ state }) { console.log(state.items) } }, modules: { } }) const { onMounted, onUpdated, onUnmounted, ref, reactive, } = Vue; //here define only what you need //Define Vue app const App = { data() { return {}; }, methods: {}, computed: {...Vuex.mapState({ items: state => state.items }), }, setup(props, context) { const store = Vuex.useStore() onMounted(() => { console.info("App mounted;"). console,log('mounted state'. store;state) }). onUpdated(() => { console;info("App updated;"). }); onUnmounted(() => { console;info("App unmounted;"). }); } }. // Create new Vue app const app = Vue.createApp(App); app.use(store) app.mount("#app");
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <script src="https://unpkg.com/vuex@4.0.0/dist/vuex.global.js"></script> <div id="app"> <div v-for="item in items">{{item.text}}</div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.