Vue Prop attribute (parent to child)

Transmitting data to the sub-assembly by Prop

The first step parent components

<template>
  <div id="app">
        <Users :users="users"></Users>
  </div>
</template>
<script>
import Users from './components/Users'
export default {
  name: 'App',
  data: function () {
    return {
      users: [
        {id:1, name:'Henry'},
        {id:2, name:'Tom'}
      ]
    }
  },
  components: {
    Users
  }
}
</script>

Explanation: The parent components of data users:[ ]by v-bind:users = "users"transmitting to the sub-assembly

Sub-assemblies

<template>
    <div id="app">
        <span>通过import注册局部组件</span><br>
        <span>{{users[0].name}}</span>
    </div>
</template>
<script>
export default {
    name: 'users',
    //props:['users'],
    props: {
        users: {
            type: Array,
            required: true
        }
    }
}
</script>

Explanation: The parent components pass over the values ​​can be used directly<span>{{users[0].name}}</span>

Prop Type

Listed in the form of a string array prop:

props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

Prop lists as objects, the names and values ​​of these attributes are the name and type of each prop:

props: {
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object
}

A second recommended

Pass dynamic or static prop

To prop passed a static value:

    <blog-post title="My journey with Vue"></blog-post>

prop dynamically assigned by v-bind, for example:

<!-- 动态赋予一个变量的值 -->
<blog-post v-bind:title="post.title"></blog-post>
<!-- 动态赋予一个复杂表达式的值 -->
<blog-post v-bind:title="post.title + ' by ' + post.author.name"></blog-post>

Any type of value can be passed to a prop

Unidirectional data flow

Prop parent will flow down to update subassembly, but not vice versa.
There are two common attempt to change a prop of the case:
the prop is used to pass an initial value; this subassembly next want to use it as a local data prop. In this case, a better definition of properties and the local data as its initial value prop

props: ['initialCounter'],
data: function () {
  return {
    counter: this.initialCounter
  }
}

The prop with a primitive values ​​passed and the need for conversion. In this case, it is preferable to use this value to define a prop calculated properties:

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

Guess you like

Origin www.cnblogs.com/guangzan/p/11268930.html
Recommended