VUE JS 使用組件實現(xiàn)雙向綁定的示例代碼
1.VUE 前端簡單介紹
VUE JS是一個簡潔的雙向數(shù)據(jù)綁定框架,他的性能超過ANGULARJS,原因是實現(xiàn)的機(jī)制和ANGULARJS 不同,他在初始化時對數(shù)據(jù)增加了get和set方法,在數(shù)據(jù)set時,在數(shù)據(jù)屬性上添加監(jiān)控,這樣數(shù)據(jù)發(fā)生改變時,就會觸發(fā)他上面的watcher,而ANGULARJS 是使用臟數(shù)據(jù)檢查來實現(xiàn)的。
另外VUEJS 入門比ANGULARJS 簡單,中文文檔也很齊全。
2.組件實現(xiàn)
在使用vue開發(fā)過程中,我們會需要擴(kuò)展一些組件,在表單中使用,比如一個用戶選擇器。
在VUEJS 封裝時,可以使用組件和指令。
在VUEJS中有V-MODEL 這個感覺和ANGULARJS 類似,實際完全不同,沒有ANGULARJS 復(fù)雜,他沒有象ANGULARJS的 ng-model 的viewtomodel和modeltoview特性,而且這個v-model 只能在input checkbox select 等控件上進(jìn)行使用,而 angularjs 可以 擴(kuò)展 ngmodel實現(xiàn)他的render方法。。
另外我在使用 VUE指令時,實現(xiàn)雙向綁定,這個我研究了自定義指定的寫法,可能還是不太熟悉的原因,還沒有實現(xiàn)。
我改用組件來實現(xiàn):
Vue.component('inputText', {
props: {
'input':{
required: true
},pname: {
required: true
}},
template: '<div><input type="text" v-model.lazy="input[pname]"><button @click="init" >選擇</button></div>',
data: function () {
return {
myModel: "ray"
}
},
methods: {
init:function () {
var rtn=prompt("輸入數(shù)據(jù)!", "");
this.input[this.pname]=rtn;
}
}
})
在vue實現(xiàn)組件時,他使用的是單向數(shù)據(jù)流,在這里我們使用 對象來實現(xiàn)雙向綁定。
在上面的代碼中,有兩個屬性 :
input,pname 其中input 是一個數(shù)據(jù)對象實例,pname: 只是一個字符串。
模版代碼:
<script type="x-template" id="myTemplate">
<div >
<table border="1" width="400">
<tr>
<td>name</td>
<td>
<input-text :input="person" pname="name"></input-text>
</td>
</tr>
<tr>
<td>age</td>
<td>
<input v-model="person.age">
</td>
</tr>
</table>
<table border="1" width="400">
<tr>
<td colspan="3">
<a href="#" @click="addRow('items')" class="btn btn-primary">添加</a>
</td>
</tr>
<tr v-for="(item, index) in person.items">
<td >
<input-text :input="item" pname="school"></input-text>
</td>
<td >
<input-text :input="item" pname="year"></input-text>
</td>
<td >
<a @click="removeRow('items',index)" >刪除</a>
</td>
</tr>
</table>
{{person}}
</div>
</script>
<inputtext :input="item" pname="school"></inputtext> <inputtext :input="person" pname="name"></inputtext>
組件使用代碼,這里綁定了 item,person 數(shù)據(jù),pname 為綁定字段。
JS實現(xiàn)代碼:
var app8 = new Vue({
template:"#myTemplate",
data:{
person:{name:"",age:0,
items:[]
}
}
,
methods: {
addRow: function (name) {
this.person[name].push({school:"",year:""})
},
removeRow:function(name,i){
this.person[name].splice(i,1) ;
}
}
})
app8.$mount('#app8')
這里我們實現(xiàn)了 子表的數(shù)據(jù)添加和刪除。
界面效果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
對Vue table 動態(tài)表格td可編輯的方法詳解
今天小編就為大家分享一篇對Vue table 動態(tài)表格td可編輯的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue3+Vue Router實現(xiàn)動態(tài)路由導(dǎo)航的示例代碼
隨著單頁面應(yīng)用程序(SPA)的日益流行,前端開發(fā)逐漸向復(fù)雜且交互性強(qiáng)的方向發(fā)展,在這個過程中,Vue.js及其生態(tài)圈的工具(如Vue Router)為我們提供了強(qiáng)大的支持,本文將介紹如何在Vue 3中使用Vue Router實現(xiàn)動態(tài)路由導(dǎo)航,需要的朋友可以參考下2024-08-08
vue3+vite+ts使用require.context問題
這篇文章主要介紹了vue3+vite+ts使用require.context問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

