Vue3父子组件传值,路由传参

186 阅读1分钟

父子组件传参

父组件传向子组件

父组件:

<template>
  <main>
    <ChildComponent :param_One="state.value_One" :param_Two="state.value_Two"  :param_Three="state.value_Three" />
  </main>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import ChildComponent from '../components/ChildComponent.vue'
const state= reactive({
  value_One:'one',
  value_Two:0,
  value_Three:true,
})
</script>

子组件:

<template>
  <div>
    father to children
  </div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
const props = defineProps({
  param_One:{
    type:String,
    default:"one"
  },
  param_Two:{
    type:Number,
    require:true,
  },
  param_Three:{
    type:Boolean,
    requrie:true,
    default:false
  }
})
onMounted(()=>{
  console.log(props)
})
</script>
<style scoped>
</style>

子组件向父组件传值,传递方法

<template>  
  <button @click="allfunc">通知父组件</button>  
</template>  
  
<script setup lang="ts">  
import { defineEmits, reactive } from 'vue';  
const state = reactive({
  title:'summer'
})
// 使用 defineEmits 定义可以发出的自定义事件  
const emit = defineEmits(['childEvent', 'childEventWithData','demo']);  
  
// 触发无数据的自定义事件  
function notifyParent() {  
  emit('childEvent');  
}  
  
// 触发带有数据的自定义事件  
function notifyParentWithData() {  
  emit('childEventWithData', { message:state.title });  
}  

const demo = ()=>{
  emit('demo',{message:'msg'})
}

const allfunc = ()=>{
  notifyParent()
  notifyParentWithData()
  demo()
}
</script>

父组件

<template>  
    <ChildComponent @childEvent="handleChildEvent" @childEventWithData="handleChildEventWithData" @demo="demo_test"/>    
</template>  
  
<script setup lang="ts">   
import ChildComponent from '../components/ChildComponent.vue';  
// 处理子组件发出的不带数据的自定义事件  
function handleChildEvent() {  
  console.log('1');  
}  
// 处理子组件发出的带有数据的自定义事件  
function handleChildEventWithData(data: { message: string }) {  
  console.log(data.message);  
}  

function demo_test(data: { message: string }){
  console.log(data); 
}
</script>

路由传参

父组件

<template>  
  <button  @click="go">aboute</button>
</template>  
  
<script setup lang="ts">   
import { useRouter } from 'vue-router';
const router = useRouter()

const go = () =>{
  router.push({
    path:'/about',
    query:{
      num:1
    }
  })
}

</script>

子组件

<template>
    <div>
1111
    </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()

onMounted(()=>{
    console.log(route)
})
 
</script>

<style scoped>

</style>