简体   繁体   English

带有对象道具的 Vue 计算 setter

[英]Vue computed setter with object prop

The idea is to pass different objects to an input component, have them displayed there as CSV and be able to edit/validate the text and change the style depending on the validation results.这个想法是将不同的对象传递给输入组件,将它们显示为 CSV 并能够编辑/验证文本并根据验证结果更改样式。 Here is the code I currently have:这是我目前拥有的代码:

<div id="vue">
    <base-input :cslice="c.workspace"></base-input>
</div>

javascript: javascript:

(function () {

  Vue.component('base-input', {
    props: ['cslice'],
    data: function () {
      return {
        colors: ['red', 'white', 'yellow', 'green', 'orange', 'purple'],
        ind: 1
      }
    },
    computed: {
      str: {
        get: function () {
          return Object.values(this.cslice).join(", ");
        },
        set: function (val) {
          if(val.indexOf('0'))
            this.ind = Math.floor(this.colors.length * Math.random());
        },
      },
      styleObj: {
        get: function () {
          return { color: this.colors[this.ind] };
        },
        set: function () {

        },
      }
    },
    template: '<div><input v-model="str" :style="styleObj" type="text"/></div>'
  });

  let vue = new Vue({
    el: '#vue',
    data: {
      c: {},
    },
    created: function () {
      this.c = Object.assign({}, this.c, {
        workspace: { width: 820, height: 440 },
      });
    },

  });

})();

Here is the fiddle: https://jsfiddle.net/tfoller/sz946qe2/3/这是小提琴: https : //jsfiddle.net/tfoller/sz946qe2/3/

This code allows me to delete the last character only if the new style is the same as the current, otherwise the text is practically uneditable, how do I fix this problem so I'm able to normally edit the input field?此代码允许我仅在新样式与当前样式相同时删除最后一个字符,否则文本实际上不可编辑,如何解决此问题以便我能够正常编辑输入字段?

Since the computed in the child uses a prop in its getter, you need to $emit back up a value with the same shape in its setter:由于 child 中的计算在其 getter 中使用了一个 prop,因此您需要在其 setter 中$emit备份一个具有相同形状的值:

set: function (val) {
   const arrValues = val.split(',').map(v => v.trim());
   console.log(arrValues);
   this.$emit('input', {
      width: arrValues[0],
      height: arrValues[1]
   })
},

That means reversing some of the string formatting stuff you were doing in order to get the right shape.这意味着颠倒一些你正在做的字符串格式化的东西,以获得正确的形状。

Listen for that input event in the parent.在父级中侦听该input事件。 You can change your prop name to value so that you can use v-model as the listener:您可以将道具名称更改为value以便您可以使用v-model作为侦听器:

<base-input v-model="c.workspace"></base-input>

Move all of the color changing functionality into a separate method in the child that's triggered by changing the input as well.将所有颜色更改功能移动到子项中的单独方法中,该方法也通过更改输入触发。 Here's a demo:这是一个演示:

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM