vue3+vite使用vuex状态管理库

1.安装vuex的依赖,npm install vuex -save
2.src新建目录与文件,如下,
vue3+vite使用vuex状态管理库_第1张图片
index.js:

import { createStore } from 'vuex'
import getters from './getters';
import settings from './modules/settings';

const store = createStore({
  modules: {
    settings,
  },
  getters
})
export default store;

getters.js:

const getters = {
    title: state => state.settings.title,
    headerTitle: state => state.settings.headerTitle,
    themeColor: state => state.settings.themeColor
};
export default getters;

settings.js

const state = {
  /**
   * @type {string}
   * @description The project title
   */
  title: '项目标题',
  /**
   * @type {string}
   * @description The Header content
   */
  headerTitle: '标题内容',
  /**
   * @type {string}
   * @description theme color
   */
  themeColor: '#409EFF',
};

const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    if (state.hasOwnProperty(key)) {
      state[key] = value;
    }
  }
};

const actions = {
  changeSetting({ commit }, data) {
    commit('CHANGE_SETTING', data);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

3.vue页面应用:a.获取全局变量,b.设置全局变量

<template>
    <div>{{headerTitle}}</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
    name: "index",
    computed: {
        ...mapGetters(['headerTitle']) // 获取
    },
    data() {},
    setup() {},
    methods: {}
}
</script>
<template>
</template>
<script>
import $store from "@/store/index"; // vuex应用

export default {
    name: 'App',
    components: {},
    watch: {
        // 监视路由
        $route(to, from) {
            // 设置标题
            $store.dispatch('settings/changeSetting', {
                key: 'headerTitle', // state定义的全局变量
                value: to.name      // 设置默认值
            })
        }
    }
}
</script>

你可能感兴趣的:(vue.js,javascript,前端)