簡體   English   中英

理解 VueJS 中的自定義組件和 V-Model

[英]Undestanding Custom Component and V-Model in VueJS

注意:我已經制作了這個問題的視頻版本,你可以在這里查看: https://www.loom.com/share/6a23d0791c2444068e964b388ed5497e


VueJS 文檔討論了如何將v-modelcomponents一起使用: https://v2.vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props

如果我創建了一個完全寫在文檔中的組件,它就可以正常工作。 這是代碼:

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})

但現在讓我嘗試更改該組件中道具的名稱——例如,改為bar

Vue.component('custom-input', {
  props: ['bar'],
  template: `
    <input
      v-bind:value="bar"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})

現在它只工作了一半。 也就是說,假設我將custom-input綁定到一個名為message的數據屬性,如下所示: <custom-input v-model="message"></custom-input> 如果我動態更新message的值,那么custom-input的值將更新——但只會更新一次 如果我再次更新該值,它將不會更新custom-input的值。

但是,如果我將道具名稱改回value (而不是bar ),那么每次我更新message的值時, custom-input的值都會更新。

[再次,這是我正在談論的視頻描述:https://www.loom.com/share/6a23d0791c2444068e964b388ed5497e]

這是為什么? 為什么我給道具起什么名字很重要? 它是否必須命名為value因為我綁定到value屬性? 如果是這樣,為什么?

簡而言之,這里發生了什么?

謝謝。

是的,屬性必須命名為value ,因為您正在使用v-model進行綁定。 v-model是綁定屬性value和監聽事件input的縮寫。 這是一種以兩種方式綁定值的特殊用例。

所以,這完全一樣:

<custom-input v-model="user" />

和:

<custom-input :value="user" @input="user = $event" />

如果您更喜歡完整的屬性表示法:

<custom-input v-bind:value="user" v-on:input="user = $event" />

使用變量$event ,您可以直接在模板中訪問發出的值。 您還可以將不帶括號的 function 名稱寫入模板,以將發出的值作為第一個參數傳遞(例如@input="setUser" ,然后聲明方法setUser(user) )。

props is used to get data down from a parent component to a child component
$emit is used to send back data from the child to the parent
v-model is used for 2 way data binding
always make the data reactive with a return data(){return{...}}
props example:
Vue.component('product',{
  template:`
      <div>
         <item :items="items"/>
      </div>
`,
    data() {
      return{
        items:'hi'
      }
  }
})

Vue.component('item',{
  template:`
<div>
    {{items}}
</div>
`,
  props:{
    items:{
      type:String,
      required:false
    }
  }
})

var app= new Vue({
  el:"#app"
})

//in html file
<div id="app">
<product/>
</div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM