38.Vue 数字输入框组件

作者: 圆梦人生 | 来源:发表于2018-11-19 14:15 被阅读1次

效果:

image.png

案例

index.vue

<template>
  <div>
    <inputCmp v-model="inputVal"/>
  </div>
</template>
<script>
// 导入组件
import inputCmp from './inputCmp'
export default {
  components: {
    inputCmp
  },
  data(){
    inputVal: 0
  }
}
</script>

inputCmp.vue (组件)

<!--
  数字输入组件
-->
<template>
    <div>
      <button @click="reduce"> - </button>
      <input type="number" v-model="defaultVal" @change="changeInput" />
      <button @click="gaga"> + </button>
    </div>
</template>

<script>
    export default {
      data(){
        return {
          // 不能直接更父组件值,内部定义接收
          defaultVal: this.value
        }
      },
      methods: {
        // 输入框改变
        changeInput(e){
          //
          this.defaultVal = Number(e.target.value);
        },
        // 减
        reduce(){
          this.defaultVal -= 1;
        },
        // 加
        gaga(){
          this.defaultVal += 1;
        }
      },
      props: {
        // 接收外部传入的值
        value: {
          type: Number,
          default: 0
        }
      }
    }
</script>

相关文章

网友评论

    本文标题:38.Vue 数字输入框组件

    本文链接:https://www.haomeiwen.com/subject/vwaofqtx.html