码迷,mamicode.com
首页 > 其他好文 > 详细

vuex

时间:2017-06-24 10:06:40      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:export   state   ext   nbsp   comm   add   项目   demo   settime   

vuex:集中式管理数据
http://vuex.vuejs.org/

安装项目:cnpm install
安装vuex: cnpm install vuex -D

vuex提供个两个方法:
    mapActions:管理所有事件
    mapGetters:获取数据

main,js

import Vue from ‘vue‘
import App from ‘./App.vue‘

import store from ‘./store‘

new Vue({
    store,
    el: ‘#app‘,
    render: h => h(App)
})

App.vue

<template>
  <div id="app">
    <h3>welcome vuex-demo</h3>
    <input type="button" value="增加" @click="increment">
    <input type="button" value="减少" @click="decrement">
    <input type="button" value="偶数才能点击+" @click="clickOdd">
    <input type="button" value="点击异步" @click="clickAsync">

    <div>
      现在数字为: {{count}}, 它现在是 {{getOdd}}
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapActions} from vuex

  export default{
    computed:mapGetters([
      count,
      getOdd
    ]),
    methods:mapActions([
      increment,
      decrement,
      clickOdd,
      clickAsync
    ])
  }
</script>

<style>
#app {
  font-family: ‘Avenir‘, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

store.js

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex);

var state = {
    count: 10   //不能有分号
};

const mutations = {//处理const actions后的操作
    increment(state) { //处理状态(数据)变化
        state.count++;
    },
    decrement(state) {
        state.count--;
    }
};

const actions = {//接受页面的点击事件
    increment: ({ //处理你要干什么,异步请求,判断,流程控制
        commit
    }) => {
        commit(‘increment‘)  //commit是函数,提交给mutations的increment(state)
    },
    decrement: ({
        commit
    }) => {//不用箭头函数也可以
        commit(‘decrement‘);
    },
    clickOdd: ({
        commit,
        state
    }) => {
        if (state.count % 2 == 0) {
            commit(‘increment‘)//提交动作
        }
    },
    clickAsync: ({
        commit
    }) => {
        new Promise((resolve) => {//Promise是es6的
            setTimeout(function() {
                commit(‘increment‘);
                resolve();//继续向下走
            }, 1000);
        });
    }
};

const getters = {  //页面获取{{count}},{{getOdd}}
    count(state) {
        return state.count;
    },
    getOdd(state) {
        return state.count % 2 == 0 ? ‘偶数‘ : ‘奇数‘;
    }
};


//需要导出Store对象
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

 

vuex

标签:export   state   ext   nbsp   comm   add   项目   demo   settime   

原文地址:http://www.cnblogs.com/yaowen/p/7072360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!