English | 简体中文
When I was developing a company project using Vue2, because of the card-style development, each component can be individually packaged into a JS resource that is loaded into the current page via the card loader. When the card functionality is particularly complex (so complex that it can stand alone as an application), I want to get the current card root component instance in the descendant component of the current card (Similar to $root
attribute), and components like RouterLink and RouterView have to take a different approach. Of course, these can be completely simulated by provide
+ inject
, v-if
, etc. However, I wanted to make it simpler, so here it is!
# npm
npm install vue2-sub-app --save
# yarn
yarn add vue2-sub-app
# pnpm
pnpm install vue2-sub-app
// main.js
import Vue from 'vue'
import Vue2SubApp from 'vue2-sub-app'
Vue.use(Vue2SubApp)
new Vue({
/* ... */
})
<script>
import { defineSubRoot, SubRouterLink, SubRouterView } from 'vue2-sub-app'
export default defineSubRoot({
components: { SubRouterLink, SubRouterView },
props: {},
data() {
return {
/* ... */
}
},
methods: {},
})
</script>
config
: component option object.
The current component is defined as a child-root component, and all descendant components of the component can get an instance of the current component through this.$subRoot
.
<!-- Parent.vue -->
<template>
<Child />
</template>
<script>
import Child from 'Child.vue'
export default defineSubRoot({
components: { Child },
props: {},
data() {
return {
/* ... */
}
},
methods: {},
})
</script>
<!-- Child.vue -->
<script>
export default {
created() {
console.log(this.$subRoot) // this.$subRoot == the instance of Parent.vue
},
}
</script>
type: boolean
If Manually Import is used, configure this property in the exported component options to make the current component a child-root component.
export default {
isSubRoot: true, // <---
components: {},
props: {},
data() {
return {}
},
methods: {},
}
type: Array<{ path: string, component: VueComponent }>
Configure subrouting information in the exported component options.
export default defineSubRoot({
subRoutes: [
{
path: '/child-one',
component: () => import('./components/ChildOne.vue'),
},
{
path: '/child-two',
component: () => import('./components/ChildTwo.vue'),
},
],
props: {},
data() {
return {
/* ... */
}
},
methods: {},
})
type: VueComponent
The child-root component instance closest to the current component.
type: SubRoute
The current subroute.
Location of the current subroute.
Parameter of the current subroute.
type: SubRouter
The subrouter instance.
Navigate to the new subrouting location.
Replace the current subroute location.
Back up to the next subroute.
type: string
The location of the target subroute.
type: string
default: "a"
Specify which tag <SubRouterLink>
is rendered to.
Renders the component corresponding to the current subroute.