如何在Vue中使用Getter?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
使用Getter
store.js,我们在state下面加入getters里面有一个商品价格加倍的方法。
// 在分离出来的vuex文件中安装 Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 每一个Vuex仓库中只能包含一个store实例
export const store = new Vuex.Store({
state: { // 把页面显示数据写在store.js文件
goodsList: [
{ name: '赣州橙子', price: '8.8' },
{ name: '新疆哈密瓜', price: '2.0' },
{ name: '山东大枣', price: '3.2' },
{ name: '阳澄湖大闸蟹', price: '10.0' }
]
},
// getters是vuex中的计算属性对象
getters: {
//商品价格加倍;其中goodsPriceDoubble(state)中有一个state参数表示state中的数据对象
goodsPriceDoubble: state => {
let goodsPriceDoubble = state.goodsList.map(currentValue => {
return {
name: currentValue.name,
price: currentValue.price *2
}
})
return goodsPriceDoubble;
}
}
})
在page4.vue里面修改成如下:
<ul class="ul_list">
<li v-for="item in goodsPriceTwo">
<p class="name">商品:{{item.name}}</p>
<p class="price">价格:¥{{item.price}}</p>
</li>
</ul>
在computed中加入如下方法:
computed: {
goodsPriceTwo() {
//this.$store.getters.vuex getters中的对应的回调函数的函数名
return this.$store.getters.goodsPriceDoubble;
}
}
显示效果就是page4的商品价格加倍了。

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注天达云行业资讯频道,感谢您对天达云的支持。