经过上期的内容,我们已经知道了为什么要使用Vuex,以及Vuex中state和mutations的作用即用法。这期的内容是getters
getters
其实就可以简单理解为是计算属性computed
,它们的作用是相似的,特点是相似的,用法也是相似的。
当我们在获取state
中的数据时,可能想要加以修饰,比如我在state
中保存了一些商品价格,在获取的时候,我想在价格前面加上$
等价格修饰符。
我们依然以一个简单的示例示范一下getters
的用法。
在components
文件夹下新建一个Part1
组件,内容如下:
<template>
<div>
<h1>我的信息: {{ myInfo }}</h1>
</div>
</template>
<script>
export default {
name: 'MyPart',
data () {
return {
myInfo: '无'
}
},
mounted () {
this.myInfo = this.$store.getters.getMyInfo;
}
}
</script>
store/index.js
:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
curIdx: 0,
name: 'Ray',
age: '21'
},
mutations: {
setCurIdx (state, index) {
state.curIdx = index;
}
},
getters: {
getMyInfo (state) {
return `我的名字是${ state.name }, 今年${ state.age }岁`;
}
}
})
我们想实现的效果就是,在获取state
中保存的名字和年龄时,将其进行拼接。
然后我们在App.vue
里,对Part1
组件进行引入、注册和使用。
<template>
<div id="app">
<tab></tab>
<page></page>
<my-part />
</div>
</template>
<script>
import Tab from '@/components/Tab';
import Page from '@/components/Page';
import MyPart from '@/components/Part1';
export default {
name: 'App',
components: {
Tab,
Page,
MyPart
}
}
</script>
没有问题,可以正常完成我们的需求。getters
的使用还是比较简单的。
QQ:505417246
微信:18331092918
微信公众号:Code程序人生
个人博客:http://rayblog.ltd