• 如何使用vue.js组件模拟v-model指令?


    1、问题描述

          在使用v-model指令实现输入框数据双向绑定,输入值时对应的这个变量的值也随着变化;但是这里不允许使用v-model,需要写一个组件实现v-model指令效果

    <div id="user">
       <input type="text" v-model="username">
       <label>{{username}}</label>
    </div>
    
    <script>
        let v = new Vue({
           el:'#user',
           data:{
              username:'zhangsan'
           }
        })
    </script>

    2、实现源码

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>Vue模拟v-model指令</title>
    		<script src="../js/vue.js"></script>
    	</head>
    	<body>
    		<div id="datas">
    			<input-model :value="num" @inputchange="num=arguments[0]"></input-model>
    			<br>
    			<span>
    				{{num}}
    			</span>
    		</div>
    		<script>
    			Vue.component('input-model',{
    				template:`<input type="text" :svalue="cvalue" @input="updateInput">`,
    				computed: {
    					cvalue() {
    						return this.svalue 
    					}
    				},
    				props:['svalue'],
    				methods: {
    					updateInput: function(event){
    						let values = event.target.value
    						this.$emit('inputchange',values)
    					}
    				}
    			});
    			
    			let v = new Vue({
    				el:'#datas',
    				data: {
    					num:'1'
    				}
    			})
    		</script>
    	</body>
    </html>
    

    3、注意事项

    (1)父组件中使用子组件,绑定的inputchange必须小写,不能使用inputChange;

    (2)子组件中的cvalue和计算属性中的要保持一致;

    (3)子组件中的@input和父组件中的@inputchange没有必然关系;

    (4)this.$emit('inputchange',values)中的inputchange要和DOM元素中的input-model一致

    (5)父组件将num值通过props属性传到子组件中;子组件通过$emit触发当前实例上的事件,将改变的值传给父组件

  • 相关阅读:
    airflow 安装问题
    ACM-单词接龙
    ACM-AK吧!少年
    ACM-Alice and Bob
    ACM-Satellite Photographs
    ACM-Subset sum
    ACM-Special Array
    数据挖掘-回归分析
    数据库原理-数据库系统的结构
    数据库原理-几种数据模型
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13313702.html
Copyright © 2020-2023  润新知