01、main.js代码如下:
// 引入createApp用于创建Vue实例 import {createApp} from 'vue' // 引入App.vue根组件 import App from './App.vue'// 引入emitter用于全局事件总线 // import emitter from '@/utils/emitter' const app = createApp(App);// App.vue的根元素id为app app.mount('#app')
02、App.vue代码如下:
<template><div class="app"><h2 class="title">App.Vue</h2><Father/></div> </template><script lang="ts" setup name="App"> import Father from "@/view/Father.vue"; </script><style scoped> .app {background-color: #ddd;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px; }.nav-button {display: inline-block; /* 让链接显示为块级元素,以便应用宽度和高度 */padding: 10px 20px; /* 内边距 */margin: 0 5px; /* 外边距,用于按钮之间的间隔 */text-decoration: none; /* 移除下划线 */color: white; /* 文本颜色 */background-color: #007bff; /* 背景颜色 */border-radius: 5px; /* 边框圆角 */transition: background-color 0.3s; /* 平滑过渡效果 */ }.nav-button:hover {background-color: #0056b3; /* 鼠标悬停时的背景颜色 */ }.nav-button.router-link-active {background-color: #28a745; /* 当前激活(路由匹配)时的背景颜色 */ }.mai-content {/* 添加边框样式 */border: 2px solid #000; /* 边框宽度、样式和颜色 */border-radius: 5px; /* 可选:添加边框圆角 */padding: 20px; /* 可选:给内部内容添加一些内边距 */margin: 20px; /* 可选:给元素添加一些外边距,以便与其他元素隔开 */ } </style>
03、Father.vue代码如下:
<template><div class="mypage"><h3>我是父页面</h3><h4>存款:{{ money }}万</h4><h4>一辆:{{ car.brand }}车,值:{{ car.price }}万</h4><child/></div> </template><script lang="ts" name="Father" setup> //Child1中用v-model绑定数据 import {provide, reactive, ref} from "vue"; import Child from "@/view/Child.vue";//数据 let money = ref(100) let car = reactive({brand: 'BYD',price: 100 })function updateMoney(value: number) {money.value -= value; } //向后代传递数据 provide('qian', {money, updateMoney}); provide('che', car) </script><style scoped> .mypage {background-color: #ddd;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;button {margin: 0 5px;} } </style>
04、Child.vue代码如下:
<template><div class="mypage"><h3>我是子页面</h3><Grandson v-bind="$attrs"/></div> </template><script lang="ts" name="Child" setup> import Grandson from "@/view/Grandson.vue"; </script><style scoped> .mypage {background-color: #ddd;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;button {margin: 0 5px;} } </style>
05、Grandson.vue代码如下:
<template><div class="mypage"><h3>我是孙页面</h3><h4>存款:{{ money }}万</h4><h4>一辆:{{ car.brand }}车,值:{{ car.price }}万</h4><button @click="updateMoney(10)">取款10万</button></div> </template><script lang="ts" name="Grandson" setup> import {inject, provide} from "vue";//把父组件provide的数据inject注入到子组件中 let {money, updateMoney} = inject("qian", {money: 0,updateMoney: (param: number) => {} }); let car = inject("che",{brand: '自行车', price: 5} );</script><style scoped> .mypage {background-color: #ddd;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;button {margin: 0 5px;} } </style>
06、结构如下:
07、浏览器显示: