我想通过输入文字更改状态。 如果我在输入表单上输入绿色,则状态变为绿色。 我调试输入单词,但看不到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: {
}
})
答案 0 :(得分: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