官术网_书友最值得收藏!

Parent-to-child communication with Props

As we saw in the The almighty components section, our component-based app will have a tree of components, and we need them to communicate with each other. For now, we will only focus on descending, parent-to-child communication. This is accomplished with "props".

Our top-bar component needs to know who the players are, which one is currently playing, and what the current turn number is. So, we will need three props--players, currentPlayerIndex, and turn.

To add props to a component definition, use the props option. For now, we will simply list the names of our props. However, you should know that there is a more detailed notation with an object instead, which we will cover in the next chapters.

  1. Let's add the props to our component:
      Vue.component('top-bar', {
// ...
props: ['players', 'currentPlayerIndex', 'turn'],
})

In the parent component, which is the root application, we can set the props value the exact same way we would for HTML attributes.

  1. Go ahead and use the v-bind shorthand to wire the props value with the app data in the main template:
      <top-bar :turn="turn" :current-player-index="currentPlayerIndex"         
:players="players" />

Note that since HTML is case-insensitive and by convention, it is recommended to use the kebab-case (with dashes) names of our props, and the camel-case names in the JavaScript code.

Now, we can use the props in our top-bar component just like data properties. For example, you could write something like this:

Vue.component('top-bar', {
// ...
created () {
console.log(this.players)
},
})

This would print the players array sent by the parent component (our app) in the browser console.

主站蜘蛛池模板: 林州市| 收藏| 嵩明县| 淳化县| 旬邑县| 长葛市| 张家口市| 曲水县| 开封县| 盐源县| 福清市| 敦化市| 兰坪| 西峡县| 高平市| 凌云县| 荔波县| 汾阳市| 云梦县| 平武县| 阿巴嘎旗| 泰安市| 雷山县| 石屏县| 孝感市| 巨野县| 齐河县| 磐石市| 肇源县| 新闻| 洛隆县| 漠河县| 靖州| 涞源县| 北辰区| 通渭县| 普宁市| 田东县| 光泽县| 政和县| 乌拉特中旗|