Passing values between parent and child of vue component

1. prop (official)

Pass data to sub-components through Prop: We can register some custom properties on the component. When the value is passed to this property, the property becomes a property of the component instance. We use the props option in the component instance to change these The attribute is contained in it , and then we can access the value in the component instance , just like accessing the value in data. A component can have any number of props by default, and any value can be passed to any prop.

Vue.component('blog-post', {
    
    
  props: ['title'],
  template: '<h3>{
    
    { title }}</h3>'
})
<blog-post title="My journey with Vue"></blog-post>

The wording of prop:

String form:

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

Object form: When
you want each prop to have a specified value type, you can list the prop in the form of an object. The names and values ​​of these properties are the respective names and types of the props:

props: {
    
    
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise // or any other constructor
}

Prop writing in html and javascript:

html中的属性名大小写不敏感,所以浏览器会把所有大写字符解释成小写字符,
所以在使用DOM的模板时,驼峰命名法的prop需要使用等价的短横线分隔命名。
Vue.component('blog-post', {
    
    
  // 在 JavaScript 中是 驼峰式命名 的
  props: ['postTitle'],
  template: '<h3>{
    
    { postTitle }}</h3>'
})
<!--HTML 中是 短横线分隔的 -->
<blog-post post-title="hello!"></blog-post>

Pass static or dynamic prop

(1) Pass static value:

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

(2) Passing dynamic values ​​(dynamic binding through v-bind):

<!-- 动态赋予一个变量的值 -->
<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 prop:

digital:

<!-- 即便 `42` 是静态的,我们仍然需要 `v-bind` 来告诉 Vue -->
<blog-post v-bind:likes="42"></blog-post>
<!-- 用一个变量进行动态赋值。-->
<!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
<blog-post v-bind:likes="post.likes"></blog-post>

Boolean value:

<!-- 包含该 prop 没有值的情况在内,都意味着 `true`-->
<blog-post is-published></blog-post>

<!-- 即便 `false` 是静态的,我们仍然需要 `v-bind` 来告诉 Vue -->
<!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
<blog-post v-bind:is-published="false"></blog-post>

<!-- 用一个变量进行动态赋值。-->
<blog-post v-bind:is-published="post.isPublished"></blog-post>

Array:

<!-- 即便数组是静态的,我们仍然需要 `v-bind` 来告诉 Vue -->
<!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
<blog-post v-bind:comment-ids="[234, 266, 273]"></blog-post>

<!-- 用一个变量进行动态赋值。-->
<blog-post v-bind:comment-ids="post.commentIds"></blog-post>

Object:

<!-- 即便对象是静态的,我们仍然需要 `v-bind` 来告诉 Vue -->
<!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
<blog-post
  v-bind:author="{
    
    
    name: 'Veronica',
    company: 'Veridian Dynamics'
  }"
></blog-post>

<!-- 用一个变量进行动态赋值。-->
<blog-post v-bind:author="post.author"></blog-post>

Pass in all the properties of an object:

post: {
    
    
  id: 1,
  title: 'My Journey with Vue'
}
<blog-post v-bind="post"></blog-post>

Equivalent to:

<blog-post
  v-bind:id="post.id"
  v-bind:title="post.title"
></blog-post>

2. The father passes the value to the son:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <blog-li v-for='item in blogs' v-bind:item='item'></blog-li>
  </div>
  <script>
    Vue.component('blog-li',{
     
     
      props:['item'],
      //每个组件必须只有一个根元素
      template:`
        <div class='blog-li'>
          <h3>{
      
      {item.title}}</h3>
          <h2>{
      
      {item.id}}</h2>
        </div>
      `
    })
    const app = new Vue({
     
     
      el: '#app',
      data: {
     
     
        blogs: [{
     
     
            id: 1,
            title: '第一篇博文'
          },
          {
     
     
            id: 2,
            title: '第二篇博文'
          },
          {
     
     
            id: 3,
            title: '第三篇博文'
          }
        ]
      }
    })
  </script>
</body>
</html>

running result:
Insert picture description here
Insert picture description here

The child component passes values ​​like the parent component: (listening to child component events)

The child component transmits a signal to the parent component, and the parent component receives the signal to perform operations.

The child component changes the value of the parent component (the child component passes the value to the parent component, and the parent component uses the value for processing, and then acts on the child component through Prop);

子组件与父组件之间需要进行沟通,官方案例:子组件中添加一个按钮点击改变博文的字体大小。
思路:父组件添加一个blogFontSize数据,使用在子组件模板中控制子组件博文字体大小。每个模板需求里面有一个按钮可以控制博文大小。

Vue provides a custom event system, and the parent component can listen to any event of the child component instance through v-on. At the same time, child components can trigger events by calling the built-in $emit method and passing in the event name :

子组件:v-on:click="$emit('enlarge-text')"
			emit中文发射的意思,可以将其理解成子组件向父组件发射信号
			
父组件:v-on:enlarge-text="blogFontSize += 0.1"  监听器,父级组件就能接收并更新blogFontSize得值。
		   理解为 父元素接收信号
<!DOCTY<!DOCTYPE html>
  <html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <!-- v-on:enlarge-text 理解为 父元素接收信号-->
      <div class="box" :style="{fontSize:blogFontSize+'px'}">
        <blog-li v-for='item in blogs' v-bind:item='item' v-on:enlarge-text='blogFontSize+=10' :size='blogFontSize'>
        </blog-li>
      </div>
    </div>
    <script>
      Vue.component('blog-li', {
    
    
        props: ['item', 'size'],
        //每个组件必须只有一个根元素  emit中文发射的意思,可以将其理解成子组件向父组件发射信号
        template: `
        <div class='blog-li'>
          <button v-on:click="$emit('enlarge-text')">点击字体变大{
     
     {size}}</button>
          <h3>{
     
     {item.title}}</h3>
          <h2>{
     
     {item.id}}</h2>
        </div>
      `
      })
      const app = new Vue({
    
    
        el: '#app',
        data: {
    
    
          blogFontSize: 16,
          blogs: [{
    
    
              id: 1,
              title: '第一篇博文'
            },
            {
    
    
              id: 2,
              title: '第二篇博文'
            },
            {
    
    
              id: 3,
              title: '第三篇博文'
            }
          ]
        }
      })
    </script>
  </body>

  </html>

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43812504/article/details/114700149