您好,登錄后才能下訂單哦!
怎么在Vue.js中實現組件間的循環引用?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
main.js
import Vue from 'vue' import App from './App' new Vue({ el: '#app', template: '<App/>', components: { App } })
main.js 導入 App 組件,并在 components 中注冊 App 組件。
App.vue
<template> <div id="app"> <li v-for="folder in folders"> <tree-folder v-bind:folder="folder"></tree-folder> </li> </div> </template> <script> import TreeFolder from './components/tree-folder' export default { data: function () { return { folders: [ { name: 'folder1', children: [{ name: 'folder1 - folder1', children: [{ name: 'folder1 - folder1 - folder1' }] }, { name: 'folder1 - folder2', children: [{ name: 'folder1 - folder2 - folder1' }, { name: 'folder1 - folder2 - folder2' }] }] }, { name: 'folder 2', children: [{ name: 'folder2 - folder1', children: [{ name: 'folder2 - folder1 - folder1' }] }, { name: 'folder2 - folder2', children: [{ name: 'folder2-content1' }] }] }, { name: 'folder 3', children: [{ name: 'folder3 - folder1', children: [{ name: 'folder3 - folder1 - folder1' }] }, { name: 'folder3 - folder2', children: [{ name: 'folder3-content1' }] }] } ] } }, components: { TreeFolder } } </script>
App 組件導入 TreeFolder 組件,并在 components 中注冊 TreeFolder 組件。
components/tree-folder.vue
<template> <p> <span>{{ folder.name }}</span> <tree-folder-contents :children="folder.children"></tree-folder-contents> </p> </template> <script> // 官方文檔:「在我們的例子中,將 tree-folder 組件做為切入起點。我們知道制造矛盾的是 tree-folder-contents 子組件,所以我們在 tree-folder 組件的生命周期鉤子函數 beforeCreate 中去注冊 tree-folder-contents 組件」 export default { props: ['folder'], data: function () { return {} }, beforeCreate: function () { // 官方文檔給出的是require // this.$options.components.TreeFolderContents = require('./tree-folder-contents.vue') // 在基于vue-cli@2.8.1按照上面的寫法還是會報錯 // Failed to mount component: template or render function not defined. // 所以我們應該改為基于es6的寫法異步加載一個組件如下 this.$options.components.TreeFolderContents = () => import('./tree-folder-contents.vue') } } </script>
TreeFolder 組件導入 TreeFolderContents 組件,并在 components 中注冊 TreeFolderContents 組件。
components/tree-folder-contents.vue
<template> <ul> <li v-for="child in children"> <tree-folder v-if="child.children" :folder="child"></tree-folder> <span v-else>{{ child.name }}</span> </li> </ul> </template> <script> import TreeFolder from './tree-folder' export default { props: ['children'], components: { TreeFolder } } </script>
TreeFolderContents 組件又導入 TreeFolder 組件,并在 components 中注冊 TreeFolder 組件,產生了循環引用。
看完上述內容,你們掌握怎么在Vue.js中實現組件間的循環引用的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。