vue父子组件传递数据,调用父子组件方法

1,065 阅读1分钟

父子组件传递数据

  1. 父组件传递数据给子组件,通过v-bind传递
// 父组件
<template>
  <div>
    <!-- 数字类型,布尔类型即便是静态值,也必须用v-bind 告诉vue这是一个表达式而不是一个字符串 -->
    <child title="静态的值" v-bind:age="42" :is-public="false" :list="[234,123,3423]" :love="like"></child>
  </div>
</template>
<script>
export default {
  data() {
    return {
     like:{
       sport:"basketball"
     }
    }
  },
}
</script>

子组件通过props获取父组件传递的值

//子组件
//子组件
<template>
  <div>
    
  </div>
</template>
<script>
export default {
   props:{
      title:{
        type:String,
        required: true  //校验必传字段
      },
      age:{
        type:Number,
        default:0
      }
      list:{
        type:Array,
        default:()=>([])  //省略大括号,直接返回字面量类型数组
      }
      love:{
        type:Object,
        default:function () {
          return {}
        }
      }
    }
  data() {
   
    return {
      
    }
  },
}
</script>
  1. 子组件改变父组件传递来的值,父组件通过 .sync 属性。这是一个语法糖,开启子组件调用update的方法更新父组件的数据

*在说vue 修饰符sync前,官方文档里面说vue .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 * 使用方法

父组件

 //sync属性告诉子组件,允许它修改
<child :msg.sync='n'></child>
//等同于
<child :msg="n" @update:msg="val=>n=val"></child>

子组件

//使用了sync修饰键,子组件必须通过update:props名的方式去修改父组件传递来的数据
<button @click="$emit("update:msg",msg-1)"></button>

父子组件调用方法

  1. 子组件通过调用父组件的方法修改父组件的数据
this.$emit(parentMethod,event)
//or 直接通过$parent获取父组件的方法
this.$parent.parentMethod(event)
//or 父组件传递方法给子组件     
  1. 父组件调用子组件的方法 this.$refs.refname.methodName()

举个例子

//child组件,里的有一个方法
method:{
    toggle(){
    console.log("""")
    }
}

// 父组件
<template>
  <div>
  <child ref="child"></child>
  <button @click="fatheMethod"></button>
  </div>
</template>
<script>
export default {
  data() {
    return {
    }
  },
  methods: {
    fatherMethod(){
     this.$refs.child.toggle()
    }
  },
}
</script>