vuex主要包含以下五個部分:
profile.js和
custom.js,一個根檔案
index.js
const customs = { namespaced: true, // 创建命名空间 state: { // 存储变量 showAlert: false }, mutations: { // 定义修改state方法 CHANGESHOW: (state, params) => { state.showAlert = !state.showAlert } }, actions: { // 异步调用mutations setShow: ({ commit }) => { commit('CHANGESHOW') } }, getters: { // 将数据过滤输出 bodyShow: state => state.showAlert }}export default customsprofile.js
const profile = { namespaced: true, state: { name: 'common name', age: 18, bool: false }, mutations: { CHANGEMSG: (state, params) => { state.name = params }, CHANGEAGE: (state, params) => { state.name = params }, CHANGEBOOL: (state) => { state.bool = !state.bool } }, actions: { setName: ({ commit }) => { commit('CHANGEMSG', 'Vuex common name') }, setAge: ({ commit }) => { commit('CHANGEAGE', 81) }, setBool: ({ commit }) => { commit('CHANGEBOOL') } }, getters: { vuexName: state => state.name, vuexAge: state => state.age, vuexBool: state => state.bool }}export default commonindex.js
import Vue from 'vue' import Vuex from 'vuex' // 引入子store import profile from './modules/profile' import customs from './modules/customs' // Vue.use(Vuex) const store = new Vuex.Store({ modules: { profile, customs } }) export default store // 导出store,以便于后续使用在需要使用的.vue檔案裡進行使用。方法如下index.vue
<template> <div> name: <h5>{{vuexName}}</h5> <button @click='setName'>chenge name</button> age: <h5>{{vuexAge}}</h5> <button @click='setAge'>chenge age</button> bool: <h5>{{vuexBool}}</h5> <button @click='setBool'>chenge bool</button> <br/> <span @click='setShow' style='display:inline-block;width:200px;height:30px;border:1px solid #999;border-radius:5px;text-align:center;line-height:30px;cursor: pointer;'>click me ,change showAlert</span> <em>{{bodyShow}}</em> </div> </template> <script> import { mapActions, mapGetters } from 'vuex' export default { computed: { ...mapGetters('profile', ['vuexName', 'vuexAge', 'vuexBool']), ...mapGetters('customs', ['bodyShow']) }, methods: { ...mapActions('customs', ['setShow']), ...mapActions('profile', ['setName', 'setAge', 'setBool']), } </script> <style> </style>app.js
import Vue from 'vue'; import VueRouter from 'vue-router'; // style import './../../sass/app.scss'; // Components import Main from './Main.vue'; import routes from './routes'; // store import store from './store'; // 将store挂载到Vue Vue.use(VueRouter); const router = new VueRouter({ routes, saveScrollPosition: true, }); new Vue({ router, store, ...Main }).$mount('#app');初始效果圖⬇️
點擊按鈕之後效果圖⬇️
至此,modules使用流程示範完畢! 【相關推薦:
vue.js影片教學】
以上是Vuex Module-狀態倉庫分割的使用介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!