javascript - 计算属性的动态 `v-model` - 基于路由参数

标签 javascript vue.js vuex vue-router 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>

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

无法在未定义、null 或原始值上设置响应式属性:null

我假设这是因为 v-model 中的 this 变为未定义(?)

我怎样才能让它工作?

更新

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

<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>

最佳答案

是的,你的<template>里面的一切在this范围,所以 this未定义。

v-model只是 :value 的语法糖和 @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})
    }
  }
}

编辑 如果您在 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(...)
  }
}

关于javascript - 计算属性的动态 `v-model` - 基于路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198300/

相关文章:

vue.js - 如何关闭 Vue 3 中的 productionTip 警告?

javascript - 将Vue组件绑定(bind)到vue实例

javascript - 如何使用突变对 Vuex 状态中的数据进行排序

javascript - 在 Javascript 中获取小数点后的数字

javascript - JSON 解析显示一些意外的字符错误

laravel - Tailwind Css - 在 View 滚动上扩展背景颜色

javascript - 使用命名空间模块中的 mapState 和 mapMutations

javascript - Vuejs 和 Vuex 操作 - 请求失败,状态代码为 422

javascript - Internet Explorer - Javascript 提交错误

javascript - 从 javascript 获取 IE 11 内部版本号