zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    网站
    世上本无事,庸人自扰之
    mac系招聘BBS
    新浪微博语录帝摘录
    dwz jui
    cheap vps
    facebook的开发标准
    rails的一些插件
    租房宝
    在Z10上用3G
  • 原文地址:https://www.cnblogs.com/zph666/p/7524833.html
Copyright © 2011-2022 走看看