store/index.js
import Vue from 'vue' import Vuex from 'vuex'
Vue.use(Vuex)
代码语言:javascript复制export default new Vuex.Store({
// 一开始就定义在state里面的数据,就会自动变成响应式
//如何添加数据到响应式系统
// Vue.set(添加到哪里,添加数据的类型key:(string|number),value:数据的值)
//如何响应式的删除state里面的数据
//Vue.delete(删除哪里,删除的key)
state: {
counter: 1000,
//比如还可以管理数组
students: [
{id: 110, name: 'yan', age: 18},
{id: 111, name: 'wang', age: 10},
{id: 112, name: 'zhao', age: 25},
{id: 113, name: 'li', age: 36}
]
},
mutations: {
//所有的修改都通过mutations提交
increment(state) {
state.counter
},
decrement(state) {
state.counter--
},
incrementCount(state, count) {
state.counter = count
},
addstudent(state, stu) {
state.students.push(stu)
}
},
actions: {
},
modules: {
},
getters: {
powerCounter(state) {
return state.counter * state.counter //就算属性有缓存
},
more20stu(state) {
return state.students.filter(s => s.age > 20)
},
more20stulength(state,getters) {
return getters.more20stu.length
},
moreAgestu(state) {
return function(age) {
return state.students.filter(s => s.age > age)
}
}
}
})
## App.vue ##
<template>
<div id="app">
<h2>-------app内容--------</h2>
<h2>{{message}}</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="addition"> </button>
<button @click="subtraction">-</button>
<!-- 这里我们只定义一个方法,传入不同的值 -->
<button @click="addCount(5)"> 5</button>
<button @click="addCount(10)"> 10</button>
<!-- 也可以传入一个对象 -->
<button @click="addStudent">点击添加学生</button>
<h2>-------hellovuex内容--------</h2>
<Hello-Vuex/>
<h2>-------getters的使用--------</h2>
<h2>{{$store.getters.powerCounter}}</h2>
<h2>{{$store.getters.more20stu}}</h2>
<h2>{{$store.getters.more20stulength}}</h2>
<h2>{{$store.getters.moreAgestu(25)}}</h2>
<!-- <Hello-Vuex :counter="counter"/> 以前的想显示的方法 -->
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex'
export default {
name: 'App',
components: {
HelloVuex
},
data() {
return {
message: '我是app组件',
}
},
computed: {
more20stu() {
return this.$store.state.students.filter(s => {
return s.age > 20
})
}
},
methods: {
addition() {
this.$store.commit('increment')
},
subtraction() {
this.$store.commit('decrement')
},
addCount(count) {
this.$store.commit('incrementCount', count)
},
addStudent() {
const stu = {id: 1004, name: 'zhou', age: 40}
this.$store.commit('addstudent', stu)
}
//上面的this是一种普通的提交风格
//另一种提交风格
// this.$store.commit({
// tyoe: increment
// //这里跟挂载的数据也就是payload
// count
//})
}
}
</script>
## main.js ##
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
## componentd/HelloVuex.vue ##
<template>
<div>
<h2>{{$store.state.counter}}</h2>
<h2>{{$store.getters.powerCounter}}</h2>
<h2>{{$store.getters.more20stu}}</h2>
</div>
</template>
<script>
export default {
name: 'HelloVuex',
//以前的方法,想要在app里显示子组价的counter,按如下定义
// props: {
// counter: Number
// }
}
</script>