zoukankan      html  css  js  c++  java
  • Vue封装组件标签上使用v-model完成双向绑定

    1.普通v-model实现双向绑定的使用

    <input type="text" v-model="message">

    vue在解释v-model的时候会做一个转化工作,实质是下面这样:

    <div id="app">
       <input type="text" :value="message" @input="message = $event.target.value">
       <span>{{message}}</span>
    </div>
    <script>
       var app2 = new Vue({
            el:'#app',
             data:{
                 message:"Hello Vue"
             }
       });
    </script>

    2.封装组件标签上使用v-model完成双向绑定

    仿照v-model的实现方法,在自定义组件标签上实现v-model功能
     
    子组件:
    <template>
      <div>
        <!--1 el-下拉选择框 -->
        <el-select v-model="content" @change="handleInput" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
            :disabled="item.disabled">
          </el-option>
        </el-select>
    
        <!--2 原生下拉框 -->
        <!-- <select name="" id="" v-model="content" @change="handleInput">
          <option value="11">11</option>
          <option value="22">22</option>
          <option value="33">33</option>
        </select> -->
    
        <!--3 el-输入框 -->
        <!-- <el-input v-model="content" @input="handleInput" placeholder="请输入内容"></el-input> -->
    
        <!--4 原生输入框 -->
        <!-- <input v-model="content" @input="handleInput" /> -->
      </div>
    </template>
    
    <script>
      export default {
        name: "HelloWorld",
        prop: ['newValue'],
        model: {
          event: 'input-change',
          prop: 'newValue'
        },
        data() {
          return {
            options: [{
              value: '选项1',
              label: '黄金糕'
            }, {
              value: '选项2',
              label: '双皮奶',
              disabled: true
            }, {
              value: '选项3',
              label: '蚵仔煎'
            }, {
              value: '选项4',
              label: '龙须面'
            }, {
              value: '选项5',
              label: '北京烤鸭'
            }],
            content: this.newValue
          }
        },
        methods: {
          handleInput(e) {
            this.$emit('input-change', this.content)
          }
        }
      };
    </script>
      
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    
    </style>
    父组件调用
    <HelloWorld v-model="name" />更新了:{{ name }}
    
    data(){
        return{
            name:'',
        }
    }
    结果 
    原生html 和element框架里的组件都可以实现
     
     
    我是马丁的车夫,欢迎转发收藏!
  • 相关阅读:
    spring mvc velocity多视图
    ubuntu 的远程桌面
    nhibernate 3.3 linq扩展
    MongoDB资料汇总专题[转发]
    SQLServer 2008 删除、压缩日志
    VS2012和2010 设置framework版本
    引用的程序集 没有强名称
    Xamarin for OSX – SetUp
    Xamarin devexpress datagrid 样式
    Xamarin devexpress Grid
  • 原文地址:https://www.cnblogs.com/Allen-project/p/15329354.html
Copyright © 2011-2022 走看看