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

使用mapState 辅助函数绑定表单v-model #1451

Closed
hqzh opened this Issue Nov 19, 2018 · 2 comments

Comments

Projects
None yet
2 participants
@hqzh

hqzh commented Nov 19, 2018

What problem does this feature solve?

看见文档说input表单输入绑定可以, 或者通过表单的change事件commit也可以

computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
},

但是使用使用mapState 辅助函数没有看到有暴露set和get,

What does the proposed API look like?

import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    message: state => {
       get() {
          
        },
        set(value) {
         
        }
   }
  })
}
@hsxfjames

This comment has been minimized.

hsxfjames commented Dec 8, 2018

显然文档并没有建议你直接把 vuex 的 state 绑定到输入框上,而是自己维护一个计算属性,把这个属性双向绑定到输入框。这样当你输入时就会触发 setter 从而提交(commit)你的输入值,输入框渲染时也会触发 getter 从 vuex 中读取相应的状态值。

此外, vuex 也并不建议你在 mutations 以外的地方修改它的状态值。

如果你坚持用 mapState ,那也应该是这样的:

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

甚至用上 mapMutations :

// ...
computed: {
  ...mapState([
    'obj',
  ]),
  message: {
    get () {
      return this.obj.message;
    },
    set (value) {
      this.updateMessage(value);
    },
  },
},
methods: {
  ...mapMutations([
    'updateMessage',
  ]),
},
@hqzh

This comment has been minimized.

hqzh commented Dec 11, 2018

@hsxfjames 你那种写法我知道,我的意思是我这种写法

@hqzh hqzh closed this Dec 11, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment