首页 > 其他 > 详细

vue 组件通信 provide 和 inject

时间:2020-02-17 00:46:19      阅读:97      评论:0      收藏:0      [点我收藏+]

1、简介

相比于props和emit,provide和inject为跨组件通信提供了更好的方式。

2、示例

<html>
  <head>
    <title>组件通信 provide 和 inject</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="root">
      <Test></Test>
    </div>
    <script>
      function registerPlugin() {
        Vue.component(Test, {
          template: <div>{{message}}<Test2 /></div>,
          provide() {
            return {
              elTest: this
            }
          }, // function 的用途是为了获取运行时环境,否则 this 将指向 window
          data() {
            return {
              message: message from Test
            }
          },
          methods: {
            change(component) {
              this.message = message from  + component
            }
          }
        })
        Vue.component(Test2, {
          template: <Test3 />
        })
        Vue.component(Test3, {
          template: <button @click="changeMessage">change</button>,
          inject: [elTest],
          methods: {
            changeMessage() {
              this.elTest.change(this.$options._componentTag)
            }
          }
        })
      }
      Vue.use(registerPlugin)
      new Vue({
        el: #root
      })
    </script>
  </body>
</html>

 

vue 组件通信 provide 和 inject

原文:https://www.cnblogs.com/mengfangui/p/12319265.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!