vuex中表单处理的解决方案

746 阅读1分钟

方案一

不使用语法糖

	<div id="app">
        <input type="text" :value="a" @input="change">
        <span>{{a}}</span>
    </div>
    
    <script>
    const store = new Vuex.Store({    //必须放在Vue前面,否则会报错
            state: {
                count: 0
            },
            mutations: {
                updatenum (state,value) {
                state.count=value
                }
            }
        })

        new Vue({
            el:'#app',
            store,
            data(){
                return{
                    num:0
                }
            },
            computed:{
                a(){
                    return this.$store.state.count
                }
            },
            methods:{
                change(value){
                    this.$store.commit('updatenum',value.target.value)
                }
            }
        })
    </script>

方案二

使用语法糖

    <div id="app">
        <input type="text" v-model="a">
        <span>{{a}}</span>
    </div>
    
    <script>
    	const store = new Vuex.Store({
            state: {
                count: 0
            },
            mutations: {
                updatenum (state,value) {
                state.count=value
                }
            }
        })
        
        
        new Vue({
            el:'#app',
            store,
            data(){
                return{
                    num:0
                }
            },
            computed:{
                a:{
                    get(){
                        return this.$store.state.count
                    },
                    set(value){
                        this.$store.commit('updatenum',value)
                    }
                }
            },
            
        })
        
    </script>

思考

这里之所以可以使用v-model来实现双向数据绑定,是因为修改数据不是组件修改的,而是通过commit提交修改,真正修改vuex中的state的数据是由vuexmutation来实现的,因此不属于子组件修改父组件数据的情况,但是对于其他情况,比如修改props外部数据,则不要使用v-model,最好是使用value属性与input事件或者是使用.sync修饰符来实现。