vuex
2018-08-26 本文已影响0人
黑夜的眸
main.js
const store = new Vuex.Store({
//配置
})
new Vue({
store:store,
render: h => h(App),
}).$mount('#app')
注意Vuex.Store的Store
S大写
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
increase(state){
state.count++
},
decrease(state){
state.count--
}
},
})
state 存放初始状态值
mutations 存放改变状态的函数
users.vue
<template>
<div>
<p>用户{{$route.params.id}}</p>
<p>数量:{{num}}</p>
<button @click="add">+1</button>
<button @click="dec">-1</button>
</div>
</template>
<script>
export default{
computed:{
num(){
return this.$store.state.count
},
},
mounted(){
console.log(this.$route)
},
methods:{
add(){
this.$store.commit('increase')
},
dec(){
this.$store.commit('decrease')
},
}
}
</script>
- this.$store.state.count获取状态值
- this.$store.commit('increase')调用改变状态的函数
高级用法getters
const store = new Vuex.Store({
state:{
list:[2,3,5,8,13,21]
},
getters:{
filterList(state){
return state.list.filter(item=>item >10)
}
}
})
//user.vue
<template>
<div>
<p>{{filterList}}</p>
</div>
</template>
<script>
export default{
computed:{
filterList(){
return this.$store.getters.filterList
}
},
}
</script>
this.$store.getters.filterList调用getters里的方法
高级用法actions 操作异步