0
点赞
收藏
分享

微信扫一扫

状态机 store

西红柿上校 2022-04-13 阅读 129
前端

1、安装

npm install vuex --save

2、store index.js

import Vue from "vue";
import Vuex from "vuex";
import Cart from "./Cart";   //拆分的状态机
import detail from "./detail.js";  //拆分的状态机
Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    //填写引入的状态机
    Cart: Cart,
    detail,  //挂载简写
  },
});
export default store;

3、store detail.js   

import Vue from 'vue'
export default {  //中间都是自己项目上得内容  仅参考
	namespaced: true,  //项目上自己定义的
	state() {
		return {
			data: [],
			test: {},
			detaList: []
		}
	},
	getters: {
		
	},
	mutations: {
		Jump(state, obj) {
			state.data = obj;
			localStorage.setItem('shuaix', JSON.stringify(state.data));
		},
		
	}
}

4、页面使用    都是参考 主要看store的一块

import {
		mapState,
		mapGetters,
		mapMutations
	} from "vuex";    //引入状态机

	export default {
		data() {
			return {
				
			};
		},
		computed: {
			...mapState({
				shuaix: (state) => state.detail.data,  //this.$store.state.detail.data的简写
				bool: (state) => state.Cart.ischengg,
			}),
		},
		created() {
			let shuaix = localStorage.getItem("shuaix");
			shuaix = shuaix != "null" ? JSON.parse(shuaix) : [];
			this.handleDetail(shuaix);
			let {
				category
			} = this.$route.params;
			console.log(this.shuaix);
			if (shuaix.ArtworkName) {
				this.isevery = !this.isevery;
			}
			window.scroll(0, 0);
		},
		methods: {
			...mapMutations({
				handleDetail: "detail/Jump",
				cart: "Cart/shopCart",
			}),

			}
		},
	};

 5、拿状态机中的方法 使用mapMutations   

 状态机中 detail.js

import Vue from 'vue'
export default {
	namespaced: true,
	state() {
		return {
			data: [],
			test: {},
			detaList: []
		}
	},
	getters: {
		
	},
	mutations: {
		Jump(state, obj) {   //拿jump方法
			state.data = obj;
			localStorage.setItem('shuaix', JSON.stringify(state.data));
		},
		
	}
}
举报

相关推荐

0 条评论