简介

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

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

vue父组件向子组件传值_vue

方式

父组件可以向子组件传递的值有三种类型

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

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

父组件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有两种接收父组件传递的参数语法。

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

第二种:我们也可以在传递值的时候对prop进行校验。

常见的类型:

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

上面的Props可以改成如下

   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,
        }
  },


快送门:各种学习资料与大厂招聘

博主:测试生财(一个不为996而996的测开码农)

座右铭:专注测试开发与自动化运维,努力读书思考写作,为内卷的人生奠定财务自由。

内容范畴:技术提升,职场杂谈,事业发展,阅读写作,投资理财,健康人生。

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

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

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

微信公众号:测试生财(定期分享独家内容和资源)

vue父组件向子组件传值_父子组件_02