用vue.js組件模擬v-model指令實(shí)例方法
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)文章
Python編程在flask中模擬進(jìn)行Restful的CRUD操作
今天小編就為大家分享一篇關(guān)于Python編程在flask中模擬進(jìn)行Restful的CRUD操作,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
YOLOv5在圖片上顯示統(tǒng)計(jì)出單一檢測目標(biāo)的個(gè)數(shù)實(shí)例代碼
各位讀者首先要認(rèn)識到的問題是,在YOLOv5中完成錨框計(jì)數(shù)是一件非常簡單的工作,下面這篇文章主要給大家介紹了關(guān)于YOLOv5如何在圖片上顯示統(tǒng)計(jì)出單一檢測目標(biāo)的個(gè)數(shù)的相關(guān)資料,需要的朋友可以參考下2023-03-03
Python面向?qū)ο蟪绦蛟O(shè)計(jì)示例小結(jié)
這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計(jì),結(jié)合實(shí)例形式總結(jié)分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中比較常見的類定義、實(shí)例化、繼承、私有變量等相關(guān)使用技巧與操作注意事項(xiàng),需要的朋友可以參考下2019-01-01
詳解Python如何利用pdfplumber提取PDF中的表格
pdfplumber 是一個(gè)開源的 python 工具庫 ,它可以輕松的獲取 PDF 文本內(nèi)容、標(biāo)題、表格、尺寸等各種信息,今天來介紹如何使用它來提取 PDF 中的表格,文中通過代碼和圖片講解的非常詳細(xì),需要的朋友可以參考下2024-04-04
Python實(shí)現(xiàn)從log日志中提取ip的方法【正則提取】
這篇文章主要介紹了Python實(shí)現(xiàn)從log日志中提取ip的方法,涉及Python文件讀取、數(shù)據(jù)遍歷、正則匹配等相關(guān)操作技巧,需要的朋友可以參考下2018-03-03

