vue之vuex

存放位置 src/store

状态 state.js 管理

mutations.js

mutation-types.js:存储mutations相关的常量

actions.js:t异步操作异步修改或者对mutations进行封装

getters.js:对state进行映射

步骤

1: state.js    定义state={}

   const state={

       singer:{}    //需要记录的状态数据

   }

  export defalut{}

2: mutation-types.js       对mutation进行修改设置

    export const SET_SINGER="SET_SINGER"              //定义一个常量

3:mutaions.js    定义修改的操作

import * as types from  './mutaion-types'   //从mutaion-types拿到常量

const mutations={             // mutation相关的修改方法

        [types.SET_SINGER](state,singer) {        //SET_SINGER为mutation-types.js定义的常量,(state,js)为state.js定义的数据,singer为提交的参数
  state. singer= singer

 }

 }

export default mutations

4:getters.js 映射state数据

export const singer=state=>state.singer

5:store/index.js文件初始化   <--安装vuex-->

/*入口文件*/
import Vue  from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
/*应用插件 方便看到修改日志*/
import createLogger from 'vuex/dist/logger'

Vue.use(Vuex)

export default new Vuex.Store({
actions,
getters,
state,
mutations,
})

6:main.js修改

/*注入store*/

import store from './store'

new Vue({
  el: '#app',
  store,   //新注册
  router,
  render: h => h(App)

})

==========================以上为初始化完成============================

使用:(使用案例为父组件(parent.vue)跳转(child.vue)子组件 文章列表跳转文章详情)

1、parent.vue 数组提交写入store中

import {mapMutations} from 'vuex'

 methods:{

  selectItem(item){
        this.$router.push({
      path:`/mtindex/${item.id}`
         });
         this. setSinger(item.id);  //写入store中         
    },
...mapMutations({     //对象映射
    setSinger:'SET_SINGER'     对应的是mutation-types对应的常量'SET_SINGER
  })  
  }

2、child.vue取数据

import {mapGetters} from 'vuex'

computed:{  
      ...mapGetters([
        'singer'   //实际对应的store/getters.js中的singer
           ]),
     },

created(){

 console.log(this.singer)  //即可以打印

}



猜你喜欢

转载自blog.csdn.net/lsy__lsy/article/details/79891899