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 存在冲突 #46

Open
Twlig opened this issue Mar 17, 2022 · 0 comments
Open

如何解决双向绑定和 vuex 存在冲突 #46

Twlig opened this issue Mar 17, 2022 · 0 comments
Labels

Comments

@Twlig
Copy link
Owner

Twlig commented Mar 17, 2022

双向绑定和 vuex 存在冲突

当在严格模式中使用 Vuex 时,在属于 Vuexstate 上使用 v-model 会导致出错。

<input v-model="obj.message">

假设这里的 obj 是在计算属性中返回的一个属于 Vuex store 的对象,在用户输入时,v-model 会试图直接修改 obj.message。在严格模式中,由于这个修改不是在 mutation 函数中执行的, 这里会抛出一个错误。

方法一:不使用v-model + 在input事件中执行commit

<input :value="message" @input="updateMessage">
//组件中
computed: {
  ...mapState({
    message: state => state.obj.message
  })
},
methods: {
  updateMessage (e) {
    this.$store.commit('updateMessage', e.target.value)
  }
}

//mutation中
mutations: {
  updateMessage (state, message) {
    state.obj.message = message
  }
}

方法二:v-model+计算属性

<input v-model="message">
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

原文:vuex和双向绑定存在冲突

@Twlig Twlig added the Vue label Mar 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant