App.vue 632 B

123456789101112131415161718192021222324252627282930
  1. <template>
  2. <h2>provide 和 inject</h2>
  3. <p>当前的颜色: {{ color }}</p>
  4. <button @click="color='red'">红色</button>
  5. <button @click="color='yellow'">黄色</button>
  6. <button @click="color='green'">绿色</button>
  7. <hr>
  8. <Child></Child>
  9. </template>
  10. <script lang="ts">
  11. import { defineComponent, provide, ref } from "vue";
  12. import Child from "./components/Child.vue"
  13. export default defineComponent({
  14. //实现跨层级组件(祖孙)之间通信
  15. setup() {
  16. const color = ref("red");
  17. provide('color',color)
  18. return {
  19. color,
  20. };
  21. },
  22. components: {
  23. Child
  24. }
  25. });
  26. </script>
  27. <style scoped>
  28. </style>