getters
Home.vue
<template>
<div class="home">
<h2>这是在单页模板中应用</h2>
<h3>count:{
{count}}</h3>
<h3>计算属性:{
{mypow}}</h3>
<button @click="count--">-</button>
<button @click="count++">+</button>
<hr>
<h2>使用全局的状态管理</h2>
<h3>Num:{
{$store.state.num}}</h3>
<h3>state中的平方{
{vuexpow}}</h3>
<h3>使用getter中的计算属性:{
{$store.getters.vxnumpow}}</h3>
<button @click="$store.state.num--">-</button>
<button @click="$store.state.num++">+</button>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
},
data() {
return {
count: 2
}
},
computed: {
mypow() {
return this.count*this.count
},
vuexpow() {
return this.$store.state.num * this.$store.state.num
}
}
}
</script>
index.js
import {
createStore } from 'vuex'
export default createStore({
state: {
//任何地方都可使用这个状态管理
num: 2,
mnum: 0,
cartlist: [
{
name: '1',price: 24},
{
name: '2',price: 12},
{
name: '3',price: 42},
{
name: '4',price: 55},
]
},
getters: {
//第一个参数就是state
vxnumpow(state) {
return state.num * state.num;
},
},
mutations: {
},
actions: {
},
modules: {
}
})
效果
getters里的计算属性可复用
Home.vue
<h3>购物车的总价:{
{$store.getters.totalprice}}</h3>
<h3>购物车的数量:{
{$store.getters.goodsnum}}</h3>
index.js
getters: {
//第一个参数就是state
vxnumpow(state) {
return state.num * state.num;
},
// totalprice(state) {
// return state.cartlist.reduce((s,n)=>s+n.price, 0)
// },
goodsnum(state) {
return state.cartlist.filter(n => n.price >30);
},
//复用计算属性,传getters属性
totalprice(state,getters) {
return getters.goodsnum.reduce((s,n)=>s+n.price, 0)
},
},
效果
getters若是不是固定的某个参数,想要自己传参呢,可采用下面的方式
Home.vue
<!-- 自定义传参-->
<h3>购物车的数量:{
{$store.getters.goodsself(20)}}</h3>
index.js
getters: {
goodsself(state, getters) {
// return function (price) {
// return state.cartlist.filter(n => n.price >price);
// }
//等价于
return price => state.cartlist.filter(n => n.price >price);
},
},