Vue使用.sync 實現父子元件的雙向繫結資料
阿新 • • 發佈:2019-01-09
1.前言
最近在vue 專案中有一個需求, 就是我需要根據不同的型別在頁面中放不同的元件, 元件需要跟當前頁面的資料進行雙向繫結,如果都寫在同一個頁面
程式碼會顯得比較多,畢竟我當前頁面已經7-800行程式碼了 所以我需要把一些元素定義成元件 ,封裝起來,所以就會遇到 資料的傳值繫結問題
在這裡我就分享我的方法,也許很多部落格上有過!
2.父元件
首先我們來看看官方文件 [https://cn.vuejs.org/v2/guide/components.html#sync-修飾符]
.sync 修飾符所提供的功能。當一個子元件改變了一個 prop 的值時,這個變化也會同步到父元件中所繫結
就是說我們可以直接在我們需要傳的prop後面加上 .sync
比如 我下面需要繫結 p_model,然後我在他後面加上.sync
<certificate-input
:p_model.sync='pname'>
</certificate-input>
他會擴充套件成:
<certificate-input :p_model="pname" @update:p_model="val => pname= val"></certificate-input>
父元件全部程式碼:
<template>
<div>
<certificate-input
:p_model. sync='pname'
:xi_model.sync="xiname">
</certificate-input>
</div>
</template>
import CertificateInput from '../common/CertificateInput.vue'
export default {
name: 'fathor',
components: {
CertificateInput
},
data() {
return {
pname:"" ,
xiname:""
}
}
3.子元件
上面說了一大推父元件下面我們來看看子元件怎麼寫 ?
因為我專案中使用vux 程式碼就直接複製過來改了一下
<template>
<div>
<x-input
title="姓名"
v-model="name"
></x-input>
<x-input title="身份證號"
v-model="idCard"
placeholder="請輸入身份證號"
required>
</x-input>
</div>
</template>
<script type="text/javascript">
import { XInput} from 'vux'
export default{
name:'certificateInput',
props:["p_model","xi_model"],
components:{
XInput
},
data(){
return{
name:this.p_model,
idCard:this.xi_model
}
},
watch:{
p_model(val) {
this.address = val;
},
name(val){
//設定監聽,如果改變就更新 p_model
this.$emit('update:p_model', val)
},
xi_model(val){
this.certificate = val
},
idCard(val){
this.$emit('update:xi_model', val)
}
}
}
</script>
由上面可以看出 子元件主要程式碼 就是監聽他的改變 然後觸發父元件監聽的事件
name(val){
//設定監聽,如果改變就更新 p_model
this.$emit('update:p_model', val)
}
好了 上面就是我的方法
感覺寫的好low
以後多多改善