How do I refactor v-model with get,set and toggle

2019-08-18 20:13发布

I have vue templates that is toggled each by a function for v-show and its corresponding getter and setter for v-model:

 <p>To : <span v-show="!emailToSW">{{toEmailSet}}</span>
      <input v-show="emailToSW" type="text" v-model.lazy="toEmailSet" />
      <a href="#" @click.prevent="toggleEmailTo();">{{emailToSW ? '                 

1条回答
看我几分像从前
2楼-- · 2019-08-18 21:01

I've implemented a snippet using both your code and a component to model the same things. The component should be called with value instead of v-model since the component calls componentSignal rather than emitting an input event.

You can see that they both work the same and affect the same things (I made componentSignal set the value of the variable, but it can do whatever you want it to).

new Vue({
  el: '#app',
  data: {
    emailToSW: true,
    componentGetObject: {
      toEmail: 'hello'
    }
  },
  methods: {
    toggleEmailTo() {
      this.emailToSW = !this.emailToSW;
    },
    componentSignal(obj) {
      console.log('Set', obj.pro, 'to', obj.val);
      this.componentGetObject[obj.pro] = obj.val;
    }
  },
  computed: {
    toEmailSet: {
      get() {
        return this.componentGetObject.toEmail
      },
      set(val) {
        // set does not return anything
        this.componentSignal({
          pro: 'toEmail',
          val
        })
      }
    }
  },
  components: {
    lockableInput: {
      template: '#lockable-input',
      data() {
        return {locked: false};
      },
      props: ['value', 'signal', 'pro'],
      computed: {
        proxyValue: {
          get() { return this.value; },
          set(newValue) { this.signal({pro: this.pro, val: newValue}); }
        }
      },
      methods: {
        toggleLocked() { this.locked = !this.locked; }
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <p>To : <span v-show="!emailToSW">{{toEmailSet}}</span>
    <input v-show="emailToSW" type="text" v-model.lazy="toEmailSet" />
    <a href="#" @click.prevent="toggleEmailTo();">{{emailToSW ? '                                                                     
查看更多
登录 后发表回答