【问题标题】:I could not change state of vuex我无法改变 vuex 的状态
【发布时间】:2020-10-22 03:37:30
【问题描述】:

我想通过输入来改变状态。 如果我在输入表单上放绿色,则状态变为绿色。 我调试了输入词,但我在 chrome 中看不到 vue 调试器的状态变化

在放置“绿色”、“红色”和“蓝色”后,我也遇到了突变类型错误 但我更改了 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

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: {
  }
})

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    为了使用

    import {store} from './store'

    您必须在 main.js 中定义您的商店 以这种方式。

    const store = new Vuex.Store({
    
    // store code here
    
    }}
    
    export default {store}
    
    
    

    适用于:

    import store from './store'

    const store = new Vuex.Store({
    
    // store code here
    
    }}
    
    export default store
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2018-04-16
      • 2021-04-10
      • 2020-03-08
      • 2021-09-16
      • 2021-03-05
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多