关于vuex使用及简单配合localStorage刷新数据保留

创建vue项目使用vuex
vue init webpack 项目名称
npm install vuex --save 安装vuex
vuex作用构建数据处理

localStorage刷新数据

getStateCount:function(state){
			if (state.connt!=1) localStorage.setItem('dddd',state.connt);
			return localStorage.getItem('dddd'); //数据进入缓存以便于刷新调用
		}

完整代码可以全部复制使用
创建一个store文件构建index.js

import Vue from 'vue' //引入vue
import Vuex from 'vuex' //引入vuex

Vue.use(Vuex);

// 创建Vuex实例
const store = new Vuex.Store({
	state:{
		connt:1
	},
	getters:{
		//方法调用监听state改变
		getStateCount:function(state){
			if (state.connt!=1) localStorage.setItem('dddd',state.connt);
			return localStorage.getItem('dddd'); //数据进入缓存以便于刷新调用
		}
	},
	mutations:{
		//方法处理及参数传入
		add(state){
			state.connt=state.connt+1
		},
		rem(state,n){
			state.connt=state.connt-n
		}
	},
	actions:{
		//方法参数植入
		addFun(context){
			context.commit("add");
		},
		redFun(context,n){
			context.commit("rem",n);
		}
	}
});

export default store

在main.js写入

import Vue from 'vue'
import App from './App'
import router from './router'

import store from './store' //引入

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,//vuex引入项
  components: { App },
  template: '<App/>'
})

构建一个vue文件写入

<template>
  <div class="hello">
    <h1>直接获取:{{ this.$store.state.connt }}</h1>
	<h1>getters获取:{{ this.$store.getters.getStateCount }}</h1>
	
	<p>connt中的值{{this.$store.state.connt }}</p>
	<button @click="Add()">加</button>
	<button @click="rem()">减</button>
	<div style="line-height: 80px;">
		{{count}}
	</div>
  </div>
</template>

<script>
import {mapState,mapGetters,mapActions} from 'vuex';
export default {
  name: 'HelloWorld',
  data () {
    return {}
  },
  computed:{
	...mapState({
		count:state=>state.connt
	})  
  },
  methods:{
	  Add(){
		  // this.$store.commit("add");
		  this.$store.dispatch("addFun");
	  },
	  rem(){
		  // this.$store.commit("rem");
		  var n=10;
		  this.$store.dispatch("redFun",n);
	  }
  },
  mounted() {
  	console.log(this.$store.getters.getStateCount);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值