欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

用vue.js組件模擬v-model指令實(shí)例方法

 更新時(shí)間:2019年07月05日 15:01:25   作者:翱翔天地  
在本篇文章里小編給各位整理的是關(guān)于用vue.js組件模擬v-model指令實(shí)例方法和相關(guān)代碼,需要的朋友們可以跟著學(xué)習(xí)下。

1、問題描述

在使用v-model指令實(shí)現(xiàn)輸入框數(shù)據(jù)雙向綁定,輸入值時(shí)對應(yīng)的這個(gè)變量的值也隨著變化;但是這里不允許使用v-model,需要寫一個(gè)組件實(shí)現(xiàn)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、實(shí)現(xiàn)源碼

<!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、注意事項(xiàng)

(1)父組件中使用子組件,綁定的inputchange必須小寫,不能使用inputChange;

(2)子組件中的cvalue和計(jì)算屬性中的要保持一致;

(3)子組件中的@input和父組件中的@inputchange沒有必然關(guān)系;

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

(5)父組件將num值通過props屬性傳到子組件中;子組件通過$emit觸發(fā)當(dāng)前實(shí)例上的事件,將改變的值傳給父組件

內(nèi)容擴(kuò)展:

vue.js指令v-model實(shí)現(xiàn)方法

V-MODEL 是VUE 的一個(gè)指令,在input 控件上使用時(shí),可以實(shí)現(xiàn)雙向綁定。

通過看文檔,發(fā)現(xiàn)他不過是一個(gè)語法糖。

實(shí)際是通過下面的代碼來實(shí)現(xiàn)的:

<%@ 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>

相關(guān)文章

最新評論