用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微信库:itchat的用法详解

Python微信库:itchat的用法详解

在论坛上看到了用Python登录微信并实现自动签到,才了解到一个新的Python库: itchat 库文档说明链接在这:  itchat 我存个档在我网站(主要是我打...

使用 Python 处理3万多条数据只要几秒钟

使用 Python 处理3万多条数据只要几秒钟

应用场景:工作中经常遇到大量的数据需要整合、去重、按照特定格式导出等情况。如果用 Excel 操作,不仅费时费力,还不准确,有么有更高效的解决方案呢? 本文以17个 txt 文本,3万多...

Python中index()和seek()的用法(详解)

1、index() 一般用处是在序列中检索参数并返回第一次出现的索引,没找到就会报错,比如: >>> t=tuple('Allen') >>> t...

用Python中的字典来处理索引统计的方法

最近折腾索引引擎以及数据统计方面的工作比较多, 与 Python 字典频繁打交道, 至此整理一份此方面 API 的用法与坑法备案.     索引引擎的基本工...

Python算法输出1-9数组形成的结果为100的所有运算式

问题: 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34–5 + 67–8 + 9 =...