vue学习笔记 十七、父子组件 ---> 子组件传值
|
系列导航 | ||
|---|---|---|
一、 效果
父组件定义的参数是:father params ,父组件调用子组件的时候将这个参数传递给子组件,子组件接收到参数后在页面展示。

二、 项目结构截图

三、代码:
index.js
import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import Start from '../views/Start.vue'
//路由的配置属组
//paht:路由路劲 必须以/开头 必填
//component:对应的路由组件 必填
//name:路由的名字
const routes = [
{
path: '/',
name: 'Start',
component: Start
},
{
path: '/home',
name: 'Home',
//按需引入
//如果没有访问/about 就不会加载这个组件 节约性能
component: () => import( '../views/Home.vue')
},
{
path: '/about',
name: 'About',
//按需引入
//如果没有访问/about 就不会加载这个组件 节约性能
component: () => import( '../views/About.vue')
} ,
{ //页面直接输入http://localhost:8080/Test 就可以进入test.vue页面
path: '/father',
name: 'Father',
//按需引入
//如果没有访问/about 就不会加载这个组件 节约性能
component: () => import( '../views/father.vue')
}
]
//创建路由对象
const router = createRouter({
//createWebHashHistory hash模式路径前面会多一个#号
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
father.vue
<template>
<div class="about">
<h1>This is an father page</h1>
<!--父组件向子组件传递参数 动态绑定属性 msg的值从return中找到-->
<child :msgZi ='msg' ></child>
</div>
</template>
<script>
import {defineComponent,ref} from 'vue'
import child from '../components/child/Child.vue'
export default defineComponent({
name : 'Father',
components:{
child
},
setup(){
let msg =ref('father params')
return{
msg,
}
}
})
</script>
Child.vue
<template>
<div class="about">
<h1>This is an child page</h1>
父组件传递过来的数据:{{msgZi}}
</div>
</template>
<script>
import {defineComponent,ref,onMounted} from 'vue'
export default defineComponent({
name : 'Child',
//专门接收父组件传递过来的参数
//props接收的数据不能直接改
props:{
msgZi:{
//数据校验
type:String,
//是否必传 默认是false
required:true,
//设置默认值
default:'默认值'
}
},
setup(props,ctx){
console.log(props.msgZi)
return{
}
}
})
</script>
浙公网安备 33010602011771号