代码之家  ›  专栏  ›  技术社区  ›  Roy Prins

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

  •  0
  • Roy Prins  · 技术社区  · 6 年前

    我正在构建一个组件,该组件可用于设置各种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 ,让它充满活力。这适用于设置(组件加载良好),但当尝试设置值时,我会得到以下错误:

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

    我想这是因为 this 里面 V-模型 变为未定义(?)

    我怎样才能做到这一点?

    更新

    我也很好奇为什么这不起作用(编译错误):

    <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>
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Erik Terwan    6 年前

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

    v-model 只是对 :value @input ,因此可以使用自定义事件和 价值 .

    还可以将计算属性与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(...)
      }
    }