Kry*_*tus 7 javascript vue.js vuex
我试着尽可能简单地解释它.我有类似的东西.简单的Vue根,Vuex存储和输入与导航栏ID内的v模型.
那个输入不是被动的......为什么?!
HTML
<div id="navbar">
<h2>@{{ test }}</h2>
<input v-model="test" />
</div>
Run Code Online (Sandbox Code Playgroud)
store.js
import Vuex from 'vuex'
export const store = new Vuex.Store({
state: {
test: 'test'
},
getters: {
test (state) {
return state.test
}
}
})
Run Code Online (Sandbox Code Playgroud)
Vue Root
import { store } from './app-store.js'
new Vue({
el: '#navbar',
store,
computed: {
test () {
return this.$store.getters.test
}
}
})
Run Code Online (Sandbox Code Playgroud)
cza*_*aic 22
您绑定到计算属性.要在计算属性上设置值,您需要编写get和set方法.
computed:{
test:{
get(){ return this.$store.getters.test; },
set( value ){ this.$store.commit("TEST_COMMIT", value );}
}
}
Run Code Online (Sandbox Code Playgroud)
在你的商店里
mutations:{
TEST_COMMIT( state, payload ){
state.test=payload;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您更改绑定到test的输入值时,它将触发对商店的提交,从而更新其状态.
你不想用v-model它。相反,请 @input="test"在您的输入字段和挂钩中使用methods:
test(e){
this.$store.dispatch('setTest', e.target.value)
}
Run Code Online (Sandbox Code Playgroud)
在您的商店内Vuex:
在mutations:
setTest(state, payload){
state.test = payload
},
Run Code Online (Sandbox Code Playgroud)
在actions:
setTest: (context,val) => {context.commit('setTest', val)},
Run Code Online (Sandbox Code Playgroud)
输入现在应该是反应性的,您应该在中看到结果@{{test}}
以下是我如何使用 Vuex 处理用户输入的示例: http: //codepen.io/anon/pen/gmROQq
| 归档时间: |
|
| 查看次数: |
6895 次 |
| 最近记录: |