简体   繁体   中英

I could not change state of vuex

I would like to change state by words of input. If I put green on the input form, then state become green. I debug input word but I could not see change of state from vue debugger in chrome

also I got mutation type error after put 'green','red'and 'blue' but I changed import part in main.js

import store from './store'
import {store} from './store'  //after changing like it, I could not see error but state is not changed

Main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'

Vue.config.productionTip = false

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

App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

Home.vue

<template>
  <div class="home">
    <input v-model="message" placeholder="green red blue">
    <p>Color: {{ message }}</p>
  </div>
</template>

<script>
// @ is an alias to /src


export default {
  name: 'Home',
  data(){
    return {
       message: 'Color' 
    }
  },
  watch: {
    message: function(newMessage){
       console.log(newMessage)
       if(newMessage=='green'){
          this.$store.dispatch('changeColor', newMessage)
       } else if(newMessage=='red') {
          this.$store.dispatch('changeColor', newMessage)
       } else if(newMessage=='blue') {
          this.$store.dispatch('changeColor', newMessage)
       }
    }
  },
  components: {
    
  },
  method: {

  }
}
</script>

index.js from store

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    color: null
  },
  mutations: {
    setColor(state, color) {
      state.color = color
    }
  },
  actions: {
    changeColor({commit}, color) {
      console.log(color + 'action')
      commit('setcolor', color)
    }
  },
  getters: {
    getColor(){
      return this.$state.color;
    }
  },
  modules: {
  }
})

in-order to use

import {store} from './store'

you have to define your store in main.js in this way.

const store = new Vuex.Store({

// store code here

}}

export default {store}


For:

import store from './store'

const store = new Vuex.Store({

// store code here

}}

export default store


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM