javascript Vue 3 CDN示例与VUEX 4,但是我如何访问main.js内部的存储呢?

dsekswqp  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(137)

我的应用程序结构:

> 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来工作,但是我希望将其分开。
我错过了什么,我如何使商店在主要访问?

wh6knrhe

wh6knrhe1#

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
}

您的工作示例:
一个二个一个一个

相关问题