溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

一文讀懂vue中的v-model

發(fā)布時間:2020-11-05 17:14:06 來源:億速云 閱讀:160 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章運(yùn)用簡單易懂的例子給大家介紹一文讀懂vue中的v-model,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

1. v-model原理

vue中v-model是一個語法糖,所謂的語法糖就是對其他基礎(chǔ)功能的二次封裝而產(chǎn)生的功能。簡單點(diǎn)說,v-model本身就是父組件對子組件狀態(tài)以及狀態(tài)改變事件的封裝。其實(shí)現(xiàn)原理上分為兩個部分:

通過props設(shè)置子組件的狀態(tài)
通過監(jiān)聽子組件發(fā)出的事件改變父組件的狀態(tài),從而影響子組件的props值
通過以上兩個部分,實(shí)現(xiàn)了父組件的狀態(tài)和子組件狀態(tài)進(jìn)行了綁定的效果。

1.1 demo

v-model使用示例

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title>v-model示例</title>
 <script type="text/javascript" src="vue.js"></script>
 </head>

 <body>
 <div id="app">
  <div>這里是父組件的狀態(tài):</div>
  <div >{{content}}</div>
  <Child v-model="content"></Child>
 </div>

 <template id="input">
  <div>
  <div>這里是子組件的輸入?yún)^(qū)域:</div>
  <input :value="value" @input="contentChange" />
  </div>
 </template>

 <script type="text/javascript">
 var Child = {
  template: "#input",
  props: {
  value: {
   type: String,
   required: true
  }
  },
  methods: {
  contentChange(value){
   this.$emit("input", value.target.value);
  }
  }
 };

 var vueInstance = new Vue({
  el: "#app",
  components: {Child},
  data: {
  content: ""
  }
 })
 </script>
 </body>
</html>

在瀏覽器中打開上述html頁面,可以看到實(shí)時效果:在子組件中的input框中輸入內(nèi)容可以在父組件區(qū)域?qū)崟r顯示,達(dá)到了子組件中狀態(tài)和父組件狀態(tài)實(shí)時綁定的效果。

2. 修改v-model默認(rèn)監(jiān)聽的事件和設(shè)置prop的名稱

v-model指令默認(rèn)是在子組件上設(shè)置的prop名稱是value,默認(rèn)監(jiān)聽子組件上的input事件,在上面的demo上,如果我們修改子組件contentChange函數(shù)中發(fā)出的事件名稱,在父組件中就無法實(shí)時獲取到子組件的輸入。

Vue中提供了通過在子組件上定義model屬性來修改這兩個參數(shù)名稱的功能,不過該功能需要在版本2.2以上才能使用,如下demo所示:

2.1 demo

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title>v-model示例</title>
 <script type="text/javascript" src="vue.js"></script>
 </head>

 <body>
 <div id="app">
  <div>這里是父組件的狀態(tài):</div>
  <div >{{content}}</div>
  <Child v-model="content"></Child>
 </div>

 <template id="input">
  <div>
  <div>這里是子組件的輸入?yún)^(qū)域:</div>
  <input :value="content" @input="contentChange" />
  </div>
 </template>

 <script type="text/javascript">
 var Child = {
  template: "#input",
  model: {
  prop: "content",
  event: "contentChanged"
  },
  props: {
  content: {
   type: String,
   required: true
  }
  },
  methods: {
  contentChange(value){
   this.$emit("contentChanged", value.target.value);
  }
  }
 };

 var vueInstance = new Vue({
  el: "#app",
  components: {Child},
  data: {
  content: ""
  }
 })
 </script>
 </body>
</html>

3. Vue中對v-model指令處理分析

基于Vue2.0版本,分析我們在標(biāo)簽上寫上v-model屬性到vue組件實(shí)現(xiàn)響應(yīng)的流程。

3.1 解析部分

3.1.1 在將HTML解析稱AST時,會解析HTML中標(biāo)簽的屬性

function processAttrs(el){
 ...
 name = name.replace(dirRE, '')
 // parse arg
 const argMatch = name.match(argRE)
 if (argMatch && (arg = argMatch[1])) {
 name = name.slice(0, -(arg.length + 1))
 }
 addDirective(el, name, value, arg, modifiers)
 ...
}

提取指令的名稱,v-model的指令名稱name為model,然后添加到實(shí)例的指令中

3.1.2 將指令相關(guān)內(nèi)容添加到實(shí)例指令中

export function addDirective (
 el: ASTElement,
 name: string,
 value: string,
 arg: &#63;string,
 modifiers: &#63;{ [key: string]: true }
) {
 (el.directives || (el.directives = [])).push({ name, value, arg, modifiers })
}

在實(shí)例的指令屬性中添加相應(yīng)的指令,這樣就實(shí)現(xiàn)了從html上的屬性到Vue實(shí)例上指令格式的轉(zhuǎn)換

3.2 指令設(shè)置部分

在將html解析稱AST之后,實(shí)例對應(yīng)的directives屬性上就有了我們設(shè)置的v-model相關(guān)的值,包括參數(shù)值value,name是model

3.2.1 調(diào)用指令的構(gòu)造函數(shù)

function genDirectives (el: ASTElement): string | void {
 const dirs = el.directives
 if (!dirs) return
 let res = 'directives:['
 let hasRuntime = false
 let i, l, dir, needRuntime
 for (i = 0, l = dirs.length; i < l; i++) {
 dir = dirs[i]
 needRuntime = true
 const gen = platformDirectives[dir.name] || baseDirectives[dir.name]
 if (gen) {
 // compile-time directive that manipulates AST.
 // returns true if it also needs a runtime counterpart.
 needRuntime = !!gen(el, dir, warn)
 }
 ...
}

在v-model指令的構(gòu)造函數(shù)中會根據(jù)tag的種類進(jìn)行不同的創(chuàng)建函數(shù)進(jìn)行創(chuàng)建,如果我們自定義指令需要在子組件上添加屬性,也需要在這個函數(shù)里面進(jìn)行操作

3.2.2 普通tag下的v-model指令構(gòu)造過程

function genDefaultModel 
 el: ASTElement,
 value: string,
 modifiers: &#63;Object
): &#63;boolean {
 ...
 addProp(el, 'value', isNative &#63; `_s(${value})` : `(${value})`)
 addHandler(el, event, code, null, true)
 ...
}
  • addProp在el上設(shè)置一個名稱為value的prop,同時設(shè)置其值
  • addHandler在el上設(shè)置事件處理函數(shù)
     

3.3 指令響應(yīng)變化部分

3.3.1 createPatchFunction統(tǒng)一處理指令的鉤子函數(shù)
createPatchFunction函數(shù)返回一個patch函數(shù),在patch處理過程中,會調(diào)用指令的鉤子函數(shù),包括:

bind
inserted
update
componentUpdated
unbind

4. 總結(jié)

4.1 編譯過程

從html上解析所設(shè)置的指令
通過gen*函數(shù)將指令設(shè)置到AST上
調(diào)用指令的構(gòu)造函數(shù),設(shè)置指令需要在編譯時期處理的事情

4.2 初始化過程

通過在patch函數(shù)中,調(diào)用統(tǒng)一的鉤子函數(shù),觸發(fā)指令的鉤子函數(shù),實(shí)現(xiàn)相應(yīng)的功能

關(guān)于一文讀懂vue中的v-model就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI