Vue中将组件转换为插件
目的:通常我们要频繁复用一个组件,我们可以通过在其他组件中直接import引入要用的组件,但是这样如果多个组件都要用这个需要频繁复用的组件,那就需要在每个组件里都去引入这个高频组件(频繁复用的那个组件),此时我们可以想到的处理方案有:将高频组件注册为全局组件,这样就不需要在每个组件中都去import引入了,直接<gaopinzujian ref="gaopinzujian "/>,并且如果我们要使用这个高频组件中的方法,就需要this.$refs.gaopinzujian 中的方法,首先他还是需要在每个组件中使用高频组件(只不过不用引入了),可是我们还可以更加简化,就是将高频组件转换为插件挂在Vue的原型上,我们直接调用this.$xxxx就行了
对以上进行简单解释:
1.高频组件(频繁复用组件)在每个组件中都import引入太麻烦
2.改用全局组件:虽然不用引入但是需要<gaopinzujian>的方式使用,并且调用其方法麻烦
3.改为插件:挂在Vue的原型上,直接调用原型上的方法即可
使用插件步骤如下:
- 写好插件的js代码,需要暴露一个对象,对象中包含install方法
- 在main.js中注册使用插件
- 在其他组件中使用插件
代码如下:
world.js:
// 引入要注册为插件的组件
import world from "./world.vue";
export default {
//使用插件暴露的对象中需要有install方法
install(Vue) {
// 创建一个子类
if (!Vue.prototype.$db) {
Vue.prototype.$db = {};
}
//生成world组件构造器
const worldConstructor = Vue.extend(world);
//生成world组件实例
const worldInstance = new worldConstructor();
//生成的world组件实例此时没有$el(组件结构),,将其挂在到随意一个元素上后才会有
console.log(worldInstance.$el);
//将其插入到html
document.body.appendChild(worldInstance.$el);
//挂载到实例上
Vue.prototype.$db.newdata = worldInstance;
},
};
world.vue:
<template>
<div class="worldContainer" v-show="isshow">
<h1>{{ testname }}</h1>
<h2>我是弹窗</h2>
</div>
</template>
<script>
export default {
name: "SonCom",
data() {
return {
isshow: false,
testname: "嘿嘿",
};
},
methods: {
open() {
this.isshow = true;
},
down() {
this.isshow = false;
},
},
};
</script>
<style scoped></style>
other.vue:
<template>
<div class="hellowWorldCOntainer">
<h1>我是父组件{{ father }}</h1>
<button @click="usePlugs">点击使用插件</button>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
father: "dad",
};
},
methods: {
usePlugs() {
if (this.$db.isshow == false) {
this.$db.open();
} else {
this.$db.down();
}
},
},
};
</script>
<style scoped></style>
main.js:
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
//使用插件
import world from "./components/_common/son.js";
Vue.use(world);
new Vue({
render: h => h(App),
}).$mount("#app");