用vue.js组件模拟v-model指令实例方法

yipeiwu_com6年前Python基础

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触发当前实例上的事件,将改变的值传给父组件

内容扩展:

vue.js指令v-model实现方法

V-MODEL 是VUE 的一个指令,在input 控件上使用时,可以实现双向绑定。

通过看文档,发现他不过是一个语法糖。

实际是通过下面的代码来实现的:

<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script type="text/javascript" src="vue/vue.js"></script>
</head>
<body>
 <div id="app-6">
 <input :value="person.name" @input="person.name = $event.target.value">
 <input :value="person.age" @input="person.age =$event.target.value">
 {{person}}
 </div>
 <script type="text/javascript">
 var app =new Vue({
 el: '#app-6',
 data:{
 person:{name:"ray",age:19}
 }
 })
 </script>
</body>
</html>

相关文章

python保存数据到本地文件的方法

1、保存列表为.txt文件 #1/list写入txt ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21'] file...

Python加密模块的hashlib,hmac模块使用解析

这篇文章主要介绍了Python加密模块的hashlib,hmac模块使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在写搬砖脚...

Python操作mongodb数据库的方法详解

Python操作mongodb数据库的方法详解

本文实例讲述了Python操作mongodb数据库的方法。分享给大家供大家参考,具体如下: 安装pymongo 下载pymongo: https://pypi.python.org/pa...

Python判断文件和字符串编码类型的实例

python判断文件和字符串编码类型可以用chardet工具包,可以识别大多数的编码类型。但是前几天在读取一个Windows记事本保存的txt文件时,GBK却被识别成了KOI8-R,无解...

python判断图片宽度和高度后删除图片的方法

本文实例讲述了python判断图片宽度和高度后删除图片的方法。分享给大家供大家参考。具体分析如下: Image对象有open方法却没有close方法,如果打开图片,判断图片高度和宽度,判...