大飞_dafei

导航

vuex 状态管理

vuex 状态管理demo

01) 基本目录结构(自己创建)

src
--vuex
------actions.js
------getters.js
------index.js
------mutations.js

02) src/vuex/index.js 内容

import Vue from 'vue'
import Vuex from 'vuex'

import mutations from './mutations'
import actions from './actions'
import getters from './getters'

Vue.use(Vuex);

const state = { //demo 定义所需要的属性
    count: 10
};

const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

export default store

 

03)src/vuex/mutations.js 内容

// mutations 同步函数
const mutations = {
    increment_vuex(state) {  //demo
        state.count++
    }
};

export default mutations

 

04)src/vuex/actions.js 内容

// actions 异步函数;提交使用dispatch

const actions = {};

export default actions

 

 05)src/vuex/getters.js 内容

// 相当于计算属性 computed

const getters = {};

export default getters

 

06)src/main.js 注册vuex

import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './vuex/index'

Vue.config.productionTip = false

Vue.prototype.$dafei = "我是自定义全局变量";

new Vue({
  render: h => h(App),
  router,
  store //demo
}).$mount('#app');

 

07)src/App.vue中使用

<template>
    <div id="app">
        {{ $route.meta.title}} ---我是元数据title
        <p>{{this.$store.state.count}} 使用</p>
        <input type="button" value="点击vuex" @click="increment()">
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: 'app',
        methods:{
            increment() {
                // increment_vuex 为 src/vuex/index.js mutations中的方法
                this.$store.commit('increment_vuex');
                console.log(this.$store.state.count); // 使用
            }
        }
    }
</script>

 

 辅助函数

const book={
    state:{
        bookState:"001",
        bookStateName:"大飞",
        foo: "123",
        bar: "456"
    },
    getters: {
      bookFoo: state => state.bookStateName + '123',
    },
    mutations: {
      SET_FOO: (state, newVal) => {
        state.foo = newVal;
      },
      SET_BAR: (state, newVal) => {
        state.bar = newVal;
      }
    },
    actions: {
      update({commit}, info) {
        commit('SET_BAR', info);
      }
    },

}

export { book }
View Code
// vue文件中使用
export default {
  data() {
    return {}
  },
  computed: {
    ...mapState(['book']),
    ...mapGetters(['bookFoo']),
  },
  created() {
    this.SET_FOO('abc')
    this.update('xyz')
  },
  methods: {
    ...mapMutations(['SET_FOO']),
    ...mapActions(['update']),
  },
};

 

 

 

vuex状态管理

posted on 2020-05-03 21:36  大飞_dafei  阅读(141)  评论(0编辑  收藏  举报