vue在组件中使用v-model

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<div id="app">
  <my-component v-model="msg"></my-component>
  {{msg}}
  <my-counter v-model="num"></my-counter>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
  Vue.component('my-component', {
    template: '<div><input type="text" :value="currentValue" @input="handleInput"/></div>',
    data: function () {
      return {
        // 双向绑定值
        currentValue: this.value
      }
    },
    props: ['value'],// 设置value为props属性
    methods: {
      handleInput(event) {
        var value = event.target.value;
        this.$emit('input', value);
      }
    }
  })
  Vue.component("my-counter", {
    template: `<div>
                <h1>{{value}}</h1>
                <button @click="plus">+</button>
                <button @click="minu">-</button>
            </div>`,
    props: {
      value: Number
    },
    data: function() {
      return {
        val: this.value
      }
    },
    methods: {
      plus() {
        this.val = this.val + 1
        this.$emit('input', this.val)
      },
      minu() {
        if(this.val>0){
          this.val = this.val-1
          this.$emit('input', this.val)
        }
      }
    }
  });
  new Vue ({
    el: '#app',
    data: {
      msg: 'hello',
      num: 1
    }
  })
</script>
</body>
</html>

 

参考官方文档:http://cn.vuejs.org/v2/guide/components.html#使用自定义事件的表单输入组件

参考:http://www.cnblogs.com/bldf/p/6645225.html

posted @ 2017-09-15 10:03  zph前端  阅读(221)  评论(0编辑  收藏  举报