我的应用程序结构:
> 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: {
}
})
主文件.js
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
来工作,但是我希望将其分开。
我错过了什么,我如何使商店在主要访问?
1条答案
按热度按时间wh6knrhe1#
app.use(store)
-您已将存储添加到vue示例。然后,您可以从任何组件访问此存储,例如使用:
或在
setup
中:您的工作示例:
一个二个一个一个