用于计算属性的动态“v-model” - 基于路由参数

Roy*_*ins 4 javascript vue.js vue-router vuex v-model

我正在构建一个可用于设置各种 vuex 属性的组件,具体取决于路由中传递的名称。这是它的天真要点:

<template>
  <div>
    <input v-model="this[$route.params.name]"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

请注意,我传递this[$route.params.name]给v-model, 以使其动态化。这适用于设置(组件加载正常),但是在尝试设置值时,我收到此错误:

Cannot set reactive property on undefined, null, or primitive value: null

我认为这是因为this内部v-model变得未定义(?)

我怎样才能使这项工作?

更新

我也很想知道为什么这不起作用(编译错误):

<template>
  <div>
    <input v-model="getComputed()"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  },
  methods: {
    getComputed(){
      return this[this.$route.params.name]
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

Eri*_*wan 6

是啊你里面的一切<template>是在this范围,所以this是不确定的。

v-model只是:valueand的语法糖@input,因此您可以使用自定义事件和计算属性来处理它:value。

您还可以使用带有 getter 和 setter 的计算属性;就像是

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      this.$store.commit('updateValue', { name: this.$route.params.name, value})
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑 如果你在你的 setter 中有更多的逻辑要做,我会像这样分开它,保持 getter 简单,并坚持一个计算属性;

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      switch(this.$route.params.name) {
        case 'foo':
          return this.foo(value)
        default:
          return this.bar(value)
      }
    }
  }
},
methods: {
  foo(val) {
    this.$store.commit(...)
  },
  bar(val) {
    this.$store.commit(...)
  }
}
Run Code Online (Sandbox Code Playgroud)