My goal is to update the state based on user input. For example, if the user types "green" in the input form, I want the state to change to green. However, when I tried to debug the input word using the Vue debugger in Chrome, I couldn't see any changes in the state.
I also encountered a mutation type error after inputting 'green', 'red', and 'blue'. I made some changes to the import part in the main.js file:
import store from './store'
import {store} from ./store” // After making this change, the error disappeared but the state did not change.
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: {
}
})