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