安装

npm install vuex@4 -S

  • 想要将vuex数据持久化,还需要安装vuex-along

npm install vuex-along -S

创建配置文件

image.png

  1. src/store/index.js ```javascript import {createStore} from ‘vuex’ import mutations from ‘@/store/mutations’ import state from “@/store/state”; import createVuexAlong from ‘vuex-along’

export default createStore({ state, mutations, plugins: [ createVuexAlong({ local: { list: [], }, session: { list: [“count”], } }) ] })

  1. 2. src/store/state.js
  2. ```javascript
  3. const state = {
  4. count: 0
  5. }
  6. export default state
  1. src/store/mutations.js
    1. const mutations = {
    2. add(state) {
    3. state.count++
    4. }
    5. }
    6. export default mutations

    在 main.js中引入

    ```javascript import {createApp} from ‘vue’ import App from ‘./App.vue’ import router from “@/router”; import store from ‘@/store’;

const app = createApp(App) app.use(router) app.use(store) app.mount(‘#app’)

  1. <a name="vMcWP"></a>
  2. ## 在Home.vue中使用store
  3. ```html
  4. <template>
  5. <h1>{{ msg }}</h1>
  6. <h1></h1>
  7. <button @click="$store.commit('add')">count is: {{ $store.state.count }}</button>
  8. <p>Edit <code>components/HelloWorld.vue</code> to test hot module replacement.</p>
  9. </template>
  10. <script>
  11. export default {
  12. name: 'HelloWorld',<template>
  13. <h1>这是首页</h1>
  14. <button @click="valueAdd">{{ value }}</button>
  15. </template>
  16. <script setup>
  17. import store from '@/store/index'
  18. import {computed} from "vue";
  19. const value = computed(() => store.state.count)
  20. const valueAdd = () => {
  21. store.commit('add')
  22. }
  23. </script>
  24. <style scoped>
  25. </style>
  26. props: {
  27. msg: String
  28. }
  29. }
  30. </script>