Elementui el-input implement custom v-model

Vue itself supports custom components to achieve v-model, but el-input as Elementui custom components have been implemented v-model, so if the custom components used in el-input, but the custom component also want to implement v-model , how we should do?


 

Wrong way

  1. Vue allows custom components to achieve the v-model reference may Vue custom v-model
  2. But if you want this way to make the following code to achieve v-model, it is not desirable
    • Can be used, but each time there is no value in the first page rendering time, have to manually enter the time, will trigger changes
    • This is because el-input the following in-player component has been achieved v-model custom, when the in-player to achieve again the same way, there have been two watch operation
 
<template>
  <div class="in-player-panel">
    <el-input placeholder="请输入视频vid" v-model="videoId">
      <el-button slot="append" @click="changePlayAuth">播放</el-button>
    </el-input>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'in-player',
    props: {
      value: {
        type: String,
        value: ' '
      }
    },
    data () {
      return {
        videoId: ''
      }
    },
    watch: {
      'value' (val) {
        if (val == this.videoId) { return false }
        this.videoId = val
      },
      'videoId' (val) { this.$emit('input', val) }
    }
  }
</script>

 

Right way

  1. If the custom components in both style and want to use the rule el-input, but also want the component itself to implement a custom v-model
  2. Then it should be the same as the following code, el-input do not directly use the v-model implemented in favor of its @inputfunctions


 
<template>
  <div class="in-player-panel">
    <el-input placeholder="请输入视频vid" :value="value" @input="update">
      <el-button slot="append" @click="changePlayAuth">播放</el-button>
    </el-input>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'in-player',
    props: {
      value: {
        type: String,
        value: ' '
      }
    },
    methods: {
      update (val) {
        this.$emit('input', val)
      }
    }
  }
</script>

 

Guess you like

Origin www.cnblogs.com/sexintercourse/p/12355311.html