Search code examples
vue.jsvue-composition-api

How to pass data from parent component to child component in vue composition API?


i am developing an example to learn how to use props as shown in this url :https://vuejs.org/guide/components/props.html#one-way-data-flow as shown in the code below, in App.vue, i receive an error when i try to use

<HelloWorld :name=refName/>

I revised some posts about this issue but still I could not figure out why I am receiving it. So, my questions are:

  1. How to pass value to :name from App.vue

  2. I read about props vs data, how to define data in the the parent class App.vue with composition API

App

<template>
  <HelloWorld :name=refName/>  <!-- ERROR: unexpected end of 
expression-->
</template>

<script>

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { onBeforeMount,onMounted,onUpdated,onBeforeUpdate,onActivated,onDeactivated,onBeforeUnmount,onUnmounted, ref } from 'vue'

const props = defineProps(['name_'])
const refName = ref(props.name_)
refName = "test"

</script>

helloWorld.vue

<template>
  <div class="hello">
  <h1>{{ props.name }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // props: {
  //   msg: String
  // }
}
</script>

<script setup>
import { onBeforeMount,onMounted,onUpdated,onBeforeUpdate,onActivated,onDeactivated,onBeforeUnmount,onUnmounted } from 'vue'
import { defineProps } from "vue";

const props = defineProps(['name','address','phone'])

</script>

Solution

  • refName must have been enclosed between qoutes

    <HelloWorld :name="refName"/>