Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

双向绑定和 vuex 是否冲突 #21

Open
chaijinsong opened this issue Jul 3, 2019 · 0 comments
Open

双向绑定和 vuex 是否冲突 #21

chaijinsong opened this issue Jul 3, 2019 · 0 comments

Comments

@chaijinsong
Copy link
Owner

双向数据绑定是对表带元素使用v-model指令来实现双向数据绑定的,本质上是监听用户输入事件以更新数据,不通过mutation,直接修改值

vuex则规定了修改值值必须通过mutation进行修改

上面两者其实就已经冲突了,如果v-model绑定的是vuex中的值,由于v-model直接修改该值,vuex会报错。所以如果出现这种情况可以有两种方法来解决

  1. 不使用v-model,而是使用value来指定表单的值,并且监听表单的input或者change事件,通过mutation来修改值

    <input :value="message" @input="updateMessage">
    
    // ...
    computed: {
      ...mapState({
        message: state => state.obj.message
      })
    },
    methods: {
      updateMessage (e) {
        this.$store.commit('updateMessage', e.target.value)
      }
    }
    
    // ...
    mutations: {
      updateMessage (state, message) {
        state.obj.message = message
      }
    }
  2. 使用v-model,但是v-model的值为一个计算属性,在这个计算属性的set方法中去调用mutation修改值,在get方法中去返回vuex中的state

    <input v-model="message">
      
    // ...
    computed: {
      message: {
        get () {
          return this.$store.state.obj.message
        },
        set (value) {
          this.$store.commit('updateMessage', value)
        }
      }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant