vue 组件通信 provide 和 inject


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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM