فهرست منبع

vue组件通信

zheng 20 ساعت پیش
والد
کامیت
1c0730fc7d

+ 3 - 1
20.vue3/project3/src/views/Attrs/Child.vue

@@ -3,13 +3,15 @@
     <h1 class="h-26 text-6xl">子组件</h1>
     <hr class="h-15" />
     <hr class="h-15" />
-    <GrandSon></GrandSon>
+    <GrandSon v-bind="$attrs"></GrandSon>
   </div>
 </template>
 
 <script lang="ts" setup>
 import { ref, reactive } from "vue";
 import GrandSon from "./GrandSon.vue";
+// 避免attrs自动挂载到根元素上变成多余的属性
+defineOptions({ inheritAttrs: false });
 </script>
 
 <style lang="scss" scoped>

+ 7 - 2
20.vue3/project3/src/views/Attrs/Father.vue

@@ -1,16 +1,21 @@
 <template>
   <div>
     <h1 class="h-26 text-6xl">Attrs</h1>
-    <h3 class="h-16 text-4xl"></h3>
+    <h3 class="h-16 text-4xl">我有{{ car }}辆车</h3>
     <h3 class="h-16 text-4xl"></h3>
     <hr class="h-15" />
     <hr class="h-15" />
-    <Child></Child>
+    <Child :carNum="car / 2" @back="changeCar"></Child>
   </div>
 </template>
 
 <script lang="ts" setup>
+import { ref, reactive } from "vue";
 import Child from "./Child.vue";
+let car = ref(10);
+function changeCar(val) {
+  car.value += val;
+}
 </script>
 
 <style lang="scss" scoped>

+ 7 - 0
20.vue3/project3/src/views/Attrs/GrandSon.vue

@@ -1,11 +1,18 @@
 <template>
   <div>
     <h1 class="h-26 text-6xl">孙组件</h1>
+    <h3 class="h-16 text-4xl">我继承我祖父的{{ carNum }}辆车</h3>
+    <button @click="handleClick">回传祖父组件</button>
   </div>
 </template>
 
 <script lang="ts" setup>
 import { ref, reactive } from "vue";
+defineProps(["carNum"]);
+const emit = defineEmits(["back"]);
+function handleClick() {
+  emit("back", 2);
+}
 </script>
 
 <style lang="scss" scoped>