Vue ----- provide / inject

深碍√TFBOYSˉ_ 2023-06-16 08:17 127阅读 0赞

provide / inject这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效
eg:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>slot</title>
  8. <script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
  9. </head>
  10. <body>
  11. <div id='root'>
  12. <parent>
  13. <children1>
  14. <children2></children2>
  15. </children1>
  16. </parent>
  17. </div>
  18. </body>
  19. <script>
  20. Vue.component('parent', {
  21. template: `<div> <slot></slot> </div>`,
  22. provide: {
  23. foo: 'bar'
  24. }
  25. })
  26. Vue.component('children1', {
  27. template: `<span>{ {foo}} <slot></slot> </span>`,
  28. inject: ['foo']
  29. })
  30. Vue.component('children2', {
  31. template: `<h1>{ {foo}}</h1>`,
  32. inject: ['foo']
  33. })
  34. var vm = new Vue({
  35. el: '#root',
  36. })
  37. </script>
  38. </html>

发表评论

表情:
评论列表 (有 0 条评论,127人围观)

还没有评论,来说两句吧...

相关阅读

    相关 provide/inject

    概述 `provide/inject`:简单的来说就是在父组件中通过`provide`来提供变量,然后在子组件中通过`inject`来注入变量。 需要注意的是这里不论子