1. 程式人生 > >vuex2快速入門

vuex2快速入門

for nbsp mar lin ext mac os cnblogs value san


#建立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>

vuex2快速入門