vuex2 10分钟快速入门

因为太简单了,我直接就贴代码了~

#建立store.js

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex) export default new Vuex.Store({ state: { platform: '', xxxxxx:"xxxxxxxxxxxxxxxxxxxxx" }, mutations: { SET_APP(state, platform) { state.platform = platform; }, testChangex(state, temp){ state.xxxxxx = temp; } }, actions: { setApp({commit}, platform) { commit('SET_APP', platform); }, testChangex({commit}, xxxxxx){ console.log(xxxxxx); commit('testChangex', "action change value:"+xxxxxx.a); } }, getters: { getApp: (state) => state.platform, doneTodos: state => { return state.xxxxxx; } } })

入口index.js 文件

import Vue from 'vue'
import App from './App'


import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
Vue.use(MintUI);

//  import Vuex from 'vuex';
//  Vue.use(Vuex);
/* eslint-disable no-new */

import store from '../../vuex/store';

new Vue({
  el: '#app',
  store,
  template: '<App/>',
  components: { App }
})

app.vue 组件

<template>
  <div id="app">
    <img src="./images/logo.png">
    <hello></hello>
  </div>
</template>

<script>
  import 'common/css/reset.css';
  import Hello from 'components/Hello/Hello'

  export default {
    name: 'app',
    components: {
      Hello
    },
    created(){
        let u = navigator.userAgent;

        if ( u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 ) {
          this.$store.dispatch('setApp', 'android');
        } else if ( !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ) {
          this.$store.dispatch('setApp', 'ios');
        }else{
          this.$store.dispatch('setApp', 'PC');
        }
        console.log(this.$store.state.platform);
    },
    mounted(){
       console.log('父组件调用:'+this.$store.getters.doneTodos);  //这个是子组件created 里修改的
     
    }
  }
</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;
  }
</style>

4.hello子组件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>      platform: {{platform}}</h2>
 
  </div>
</template>

<script>

 
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      platform: '-'
    }
  },
   created () {
     

      this.platform = this.$store.getters.getApp;
     // console.log(this.$store.state.platform);
      console.log(this.$store.getters.doneTodos);

      this.$store.dispatch('testChangex', {"a":'子组件传的值sssss',age:10});
       console.log(this.$store.getters.doneTodos);
  }
}
</script>

 

posted @ 2017-05-10 23:33  Yuri_trender  阅读(2123)  评论(0编辑  收藏  举报