[JS][Vue]學(xué)習(xí)記錄之props傳值(父到子)

Demo地址

如果我們需要從父的組件傳值到子組件可以用props來(lái)實(shí)現(xiàn).
首先,這里有兩個(gè)組件app.vuemyComponent.vue:

<template>
  <div id="app">
    <app-header></app-header>
    <myComponent v-bind:users="users"></myComponent>
    <app-footer/>
  </div>
</template>

<script>

import myComponent from './components/myComponent'
import header from './components/header'
import footer from './components/footer'

export default {
  name: 'App',
  components: {
      'app-header': header,
      'myComponent': myComponent,
      'app-footer' : footer
  },
  data(){
    return {
      users : ["allen","marry","tom"]
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

data中的users就代表我要傳遞的數(shù)據(jù),這里是一個(gè)名字為users數(shù)組.我們要把數(shù)據(jù)傳遞到myComponent中.

<template>
  <div class="myComponent">
    <ul>
      <li v-for="user in users">
        {{user}}
      </li>
    </ul>
  </div>
</template>
<script>
export default
{
      name: 'myComponent',
        //方式一
        // props:["users"],
        //方式二
        props:{
          users:{
              type : Array,
              required : true
            }
        }
    }
}
</script>
<style scoped>
</style>

這里兩種方式拿到父組件傳遞過(guò)來(lái)的值:

  • props:["users"]:這種方式直接就能拿到,但不夠嚴(yán)謹(jǐn).
  • props:{users:{ type : Array,required : true } },這種方式比較嚴(yán)謹(jǐn),指明了數(shù)據(jù)類型以及是否必須,官方文檔建議采用這種方式來(lái)接收值.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對(duì)于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,173評(píng)論 0 29
  • Vue 實(shí)例 屬性和方法 每個(gè) Vue 實(shí)例都會(huì)代理其 data 對(duì)象里所有的屬性:var data = { a:...
    云之外閱讀 2,365評(píng)論 0 6
  • Vue筆記系列1、Vue.js入門(mén)3、Vue.js進(jìn)階 API 以下會(huì)隨用隨記一些API,可能會(huì)不定期更新。 Vu...
    其心閱讀 2,132評(píng)論 0 10
  • 配置springmvc 1:開(kāi)啟springmvc注解模式 <mvc:annotation-driven /> 這...
    懶小松閱讀 642評(píng)論 0 0
  • 一、五大數(shù)字力回顧 首先回顧一下五大關(guān)鍵數(shù)字力思維導(dǎo)圖,如下圖所示: 我們可以整理各指標(biāo)的權(quán)重和判斷依據(jù)如下: 二...
    87a17761c1f6閱讀 277評(píng)論 0 0

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