使用vuex保存singer每个歌星的基本信息
1.建src/store文件夹,建立以下文件来存储歌星信息
2.state.js
1 const state = { 2 singer:{} 3 } 4 5 export default state
2.mutations.js
1 import * as types from './mutation-types' 2 const mutations = { 3 [types.SET_SINGER](state,singer){//mutations接收两个参数,第一个是state另外一个是传递过来的值 4 state.singer = singer 5 } 6 } 7 8 9 export default mutations
3.mutation-type.js
1 export const SET_SINGER = 'SET_SINGER'
4.getters.js
export const singer = state =>state.singer
5.index.js
1 import Vue from 'vue' 2 import Vuex from 'vuex' 3 import * as actions from './actions' 4 import * as getters from './getters'//es6的语法,可以在使用mutations里面导出的内容时候直接用mutations.点出来 5 import state from './state' 6 import mutations from './mutations' 7 Vue.use(Vuex) 8 9 export default new Vuex.Store({ 10 actions, 11 mutations, 12 getters, 13 state 14 })
6.在singer.vue中引入mapMutations from vuex,并映射到方法中,设置setSinger方法
1 import {mapMutations} from 'vuex' 2 3 4 methods:{ 5 ...mapMutations({ 6 setSinger:'SET_SINGER' 7 }), 8 }
7.在点击选择明星的时候,将点击明星的信息存储到setSinger中:
1 selectSinger(singerName){ 2 this.$router.push({ 3 path: `/singer/${singerName.id}` 4 }) 5 this.setSinger (singerName) 6 },
8.在singer-detail.vue中获取点击时候保存的明星信息:
a.引入mapGetters import {mapGetters} from 'vuex' b.将singer映射到计算属性中: computed:{ ...mapGetters([ 'singer', ]) } c.created(){}的时候打印一下singer
一辈子很短,努力的做好两件事就好;第一件事是热爱生活,好好的去爱身边的人;第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;