vue 組件 - prop

prop 是什么

prop 是你可以在組件上注冊的一些自定義特性。當一個值傳遞給一個 prop 特性的時候,它就變成了那個組件實例的一個屬性。

如何使用 prop

  1. 在組件內(nèi)部,使用 props 選項來定義好,當前組件需要用到的參數(shù)
  2. 調(diào)用組件的時候,在組件的標簽上面,通過自定義屬性來傳遞 prop
    new Vue({
      el: '#app',
      components: {
        helloWorld: {
          props: ['title'],
          data: function() {
            return {
              msg: '張三'
            }
          },
          template: `
            <div>{{ msg }}</div>
          `
        }
      }
    })
<div id="app">
  <hello-world title="我的天呀"></hello-world>
</div>

props 的定義有幾種

兩種

  1. 數(shù)組的方式
props: ['title', 'xxx']
  1. 對象的方式 (這種方式能夠?qū)崿F(xiàn) prop 的驗證)
props: {
  title: String,
  // 對象或數(shù)組默認值必須必須傳遞一個函數(shù),然后返回默認值
  xxx: {
    type: Object,
    default: function() {
      return { message: 'hello' }
    }
  },
  // 自定義驗證函數(shù)
  yyy: {
    validator: function(value) {
      return ['success', 'warning', 'danger'].indexOf(value) !== -1
    }
  }
}

非 Prop 的特性

如果使用組件時,傳遞的某個屬性,在組件中沒有定義這個屬性的prop的話,那么這個屬性就是一個 非 prop 的特性。非 prop 的特性 會自定添加到組件的 根元素 上面。

替換/合并已有的特性

默認情況下,非 prop 的特性 會直接替換 組件的 根元素 上面的相同名字的屬性。(如下代碼,最終渲染在瀏覽器中的 hello 組件的根元素的id值將會是 hhh)。但如果是 class 或者style 的話將會對兩邊的值做一個合并

Vue.component('hello', {
  template: `
    <div id="box">我的天呀</div>
  `
})
<div id="app">
  <hello id="hhh"></hello>
</div>
禁用特性繼承

如果不希望組件的根元素繼承特性,你可以設(shè)置組件的 inheritAttrs 選項為 false

Vue.component('hello', {
  inheritAttrs: false
})
$attrs 與 禁用特性繼承 來實現(xiàn) 基礎(chǔ)組件
Vue.component('base-input', {
  inheritAttrs: false,
  props: ['label', 'value'],
  template: `
    <label>
      {{ label }}
      <input
        v-bind="$attrs"
        v-bind:value="value"
        v-on:input="$emit('input', $event.target.value)"
      >
    </label>
  `
})
<base-input
  v-model="username"
  class="username-input"
  placeholder="Enter your username"
></base-input>

PS:

  1. prop 是不能主動修改的
  2. prop 定義時如果是 駝峰 命令方式,那么使用的時候需要為 短橫線 方式,與組件一樣在3種特殊情況下,不需要。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Prop prop 大小寫 單項數(shù)據(jù)流 所有的 prop 都使得其父子 prop 之間形成了一個單向下行綁定:父級...
    ChangLau閱讀 98,127評論 0 12
  • 什么是組件 組件(Component)是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用...
    angelwgh閱讀 820評論 0 0
  • 一、什么是組件(Component)? 組件(Component)是Vue.js最強大的功能之一。組件可以擴展HT...
    廖馬兒閱讀 24,561評論 1 4
  • 什么是組件? 組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝...
    youins閱讀 9,708評論 0 13
  • 組件注冊 組件名 在注冊一個組件的時候,我們始終需要給它一個名字。 該組件名就是Vue.component的第一個...
    oWSQo閱讀 458評論 0 1

友情鏈接更多精彩內(nèi)容