suppose the contents of user.vue
are as follows:
<template>...</template>
<script>
export default {
mounted () {
console.log(this);
console.log(this.$root , this.$root === this);
console.log(this.$parent , this.$root === this.$parent);
}
};
</script>
user.vue
as a normal component:
introduce:
in test.vue
<template>
<div>
<user></user>
</div>
</template>
<script>
import user from "user.vue";
export default {
components: {
user
}
}
</script>
the judgment result in the following user.vue mounted
:
console.log(this); // VueComponent
console.log(this.$root , this.$root === this); // VueComponent(test.vue); false
console.log(this.$parent , this.$root === this.$parent); // VueComponent(test.vue); false
user.vue
treat the component as a separate vue
instance through Vue.extend
:
introduce:
in test.vue
<template>
<div ref="con"></div>
</template>
<script>
import user from "user.vue";
export default {
mounted () {
let con = this.$refs.con;
let _con = document.createElement("div");
let render = document.createElement("div");
_con.appendChild(render);
let myComponent = Vue.extend(user);
new myComponent().$mount(render);
con.appendChild(_con);
}
};
</script>
the judgment result in the following user.vue mounted
:
console.log(this); // VueComponent
console.log(this.$root , this.$root === this); // VueComponent(user.vue); true
console.log(this.$parent , this.$root === this.$parent); // undefined; false
As you can see above, the Vue
subclass instantiated using Vue.extend
belongs to an individual, so it is equivalent to directly using Vue
to instantiate! It has nothing to do with the component that references them, and even if they are instantiated within a component through Vue.extend
, it has nothing to do with that component!
the actual requirement is that I need them to be associated, because only using the Vue.extend
method can render components dynamically at any dom location! And support the coexistence of multi-components! However, for example, after a component is instantiated through the Vue.extend
method, I need the instance to be nested at the normal component level as normal components do, so that properties and methods shared with other parent components can be accessed through $root
or $parent
or vuex $store
or $route in vue-router!
could you tell me how to implement it?