vue父组件向子组件传值

简介

vue中组件与组件的关系存在两类:父子组件与非父子组件。html

以下图所示,三个组件中就包含了父子组件与非父子组件两种状况,这里组件之间的交互主要由值传递和事件触发调用两种方式,这里先分享下父组件向子组件值传递。vue

方式

父组件能够向子组件传递的值有三种类型数组

  1. 属性变量或者纯文本
  2. 函数名
  3. 父组件自身实例(this)

例子

假设有两个组件App.vue和Sub1.vue,其中App.vue为父组件,Sub1.vue为子组件。app

父组件App.vue

<template>
     <!--父组件传递titile,run,home给子组件sub1-->
     <!--其中title为属性,run为方法,this为父组件实例的指针-->
     <sub1 :title="title" :run="run" :home="this"  ref="deleteConfirm"/>
</template>
<script>
//导入子组件
import Sub1 from './Sub1.vue' 
export default {
      name: 'app',
      data() {
             return {
               title : 'test' 
           }
       },methods {
             run() {
                    console.log('parent')
             }
       }, components: {
          Sub1 //挂载子组件Sub1
       }
}
</script>

子组件Sub1.vue

<template>
     <!--子组件接收父组件传过来的title-->
     <module :title="title" : ref="deleteConfirm"/>
     <!--这里点击button能够调用父组件的run方法-->
     <button :click="run()"></button>
     <!--runParent内部经过父组件的this指针调用父组件的属性和方法-->
     <button :click="runParent()"></button>
</template>
<script>
  export default {
          name: "Sub1",
          data() {
                return {
                  title: ''
             }
          },
          //1.第一种方法,用数组的方式接收父组件的传值:title,run,home
          props: ['title','run','home'],
         ,methods {
              runParent() {
                   //能够经过父组件实例this.home直接调用父组件中的方法。
                   console.log(this.home.title);
             this.home.run();
              }
         }
    }
</script>

prop接收参数

prop有两种接收父组件传递的参数语法。ide

第一种就是上面的props: ['title','run','home'],这种数组方式函数

第二种:咱们也能够在传递值的时候对prop进行校验。测试

常见的类型:this

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

上面的Props能够改为以下url

   props: {
        title: {  //接收父组件传递过来的title
             type: String,
             default() {
                  //若是父组件没有传递title变量,则使用default()获取一个默认值
                  return this.$t('commons.title')
            }
        },
        run: { //接收父组件传递过来的run方法,
             type: Function,
             default: function () {
                  console.log('hello')
             }
        },
        home: { //接收父组件自己
             type: Object,
        }
  },


博主:测试生财spa

座右铭:专一测试与自动化,致力提升研发效能;经过测试精进完成原始积累,经过读书理财奔向财务自由。

csdn:https://blog.csdn.net/ccgshigao

博客园:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374

相关文章
相关标签/搜索