1.简单的写法
这里就不过多的介绍vuex的安装和引入了(具体的可以看我的博客vuex1.0)
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state:{
testObj:{
name:'小明'
}
},
getters:{
ceshiName: state=>{
return state.testObj
}
}
})
在页面上就可以拿到这个变量了 这里就可以拿到getters所有的数据了,如果想要拿到testObj里面的数据,直接this.$store.getters.ceshiName即可
mounted:{
console.log('getters的数据',this.$store.getters)
}
上面的是简单的运用 新手可以直接复制上面的代码 慢慢理解
2.运用getters进行过滤
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state:{
goodsList:[
{
id:'1',
name:'小明'
},
{
id:'2',
name:'小紫'
},
{
id:'3',
name:'小张'
}
]
},
getters:{
goodsById:state=>(id)=>{
return state.goodsList.filter(item=>item.id == id)
}
}
})
在页面上就可以拿到这个方法进行过滤
mounted:{
console.log('过滤的数据',this.$store.getters.goodsById(2))
}
也可以借助mapGetters进行获取(这样就可以获取到goodsById的方法了)
mport { mapGetters } from 'vuex'
computed:{
...mapGetters (['goodsById'])
},
mounted:{
const goods=this.goodsById(2)
console.log('过滤的数据',goods)
}
以上就是vuex种的getters简单运用 我这上面的数据是写死的 新手理解后 可以配合state灵活运用