优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vue核心知识:8.3 vuex在vue-cli中的应用,文件之间的导出与引入

nanyue 2024-09-10 16:06:24 技术文章 5 ℃

问题:vuex在vue-cli中的应用

第一步:npm下载vuex资源包:

npm install vuex --save

第二步:在 src/main.js 中引入

import Vue from 'vue' 
import Vuex from 'vuex'
Vue.use(Vuex)
import store from './vuex/store'

第三步:在 src 下 新建 vuex 文件夹

vuex下:
	* modelus //文件夹,存放不同模块需要的共享状态文件
		*	 index.js
		*	 等
	*store.js
 *types.js

说明:

vuex文件夹下store.js:

import Vue from 'vue'
import Vuex from 'vuex'
//引入不同模块需要的共享变量:
import index from './modules/index'
//使用vuex
Vue.use(Vuex)
//对外暴露
export default new Vuex.Store({
 modules: {
 index
 }
})

vuex文件夹下 modelus文件夹下 index.js:

//引入一个常量,保证 action 和 mutations 的统一。
import * as types from '../types'
/**
 * App通用配置
 */
const state = {
	//vuex初始化值
 count : 0
}
const actions = {
 increment({ commit }, n){
 commit(types.TEST_INCREMENT, n)
 },
 decrement({ commit }, state){
 commit(types.TEST_DEREMENT, state)
 }
}
const getters = {
 count: state => state.count
}
const mutations = {
 [types.TEST_INCREMENT](state, n) {
 console.log(n);
 state.count = state.count + 5 + n
 },
 [types.TEST_DEREMENT](state, status) {
 state.count = state.count - 3
 }
}
export default {
 state,
 actions,
 getters,
 mutations
}

vuex文件夹下type.js:

//暴露常量
export const TEST_INCREMENT='TEST_INCREMENT'
export const TEST_DEREMENT='TEST_DEREMENT'

编辑器:

Tags:

最近发表
标签列表