创建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>