Vue 父传子案例简单入门

上一篇博客介绍了 Vue 中子传父的简单案例,这篇介绍一下父传子,主要通过 props 进行实现

新建 Father.vue 和 Child.vue 两个文件,在 App.vue 中引入 Father.vue,方法同上一篇博客

在 Father.vue 中引入 Child.vue,定义要传递的信息,这里简单设置为 sendMessage=“Vue父传子”

Father.vue

<template>
  <Child sendMessage="Vue父传子">Child>
template>

<script>
  import Child from "./Child";
  export default {
      
    name: "Father",
    components:{
      
      Child
    }
  }
script>

<style scoped>

style>

在子组件中接收数据,sendMessage 需要在 props 中进行声明,有两种方式,一种通过数组形式,另一种通过对象形式,对象形式可指定 sendMessage 为 String 类型

Child.vue

<template>
  <div>
    <h1>
      子组件:{
    { sendMessage }}
    h1>
  div>
template>

<script>
  export default {
      
    name: "Child",
    // 接收父组件传递的数据
    // props:["sendMessage"]
    props:{
      
      sendMessage:String
    }
  }
script>

<style scoped>

style>

运行项目可以看到 “子组件:” 后面已经接收到父组件传递的 “Vue父传子” 信息
Vue 父传子案例简单入门_第1张图片

你可能感兴趣的:(Vue,vue)