01-创建一个好的组件
02-在js文件创建函数
html
<!--
* @Author: Allyn
* @Description:
* @Date: 2022-02-05 19:47:40
* @LastEditTime: 2022-02-05 20:05:03
* @FilePath: \hmYouGou\components\test.vue
-->
<template>
<div v-show="isshow">
<div class="box">{{text}}</div>
</div>
</template>
<script>
export default {
name: 'HmyougouTest',
data() {
return {
text: '我式一个组件',
isshow: false,
};
},
methods: {
show() { //显示
this.isshow = true
},
hide() { //隐藏
this.isshow = false
}
}
};
</script>
<style>
.box {
position: relative;
top: 50%;
left: 50%;
}
</style>
js
/*
* @Author: Allyn
* @Description:
* @Date: 2022-02-05 19:53:00
* @LastEditTime: 2022-02-05 20:31:21
* @FilePath: \item\src\components\test.js
*/
import vue from 'vue'
import test from './test.vue' //组件对象
/* 01.通过extend创建一个组件构造函数 */
const TestTemplate = vue.extend(test)
/**
* @description:
* @arguments:
* @param {*} dom 需要挂载到哪个dom下
*/
export function showTest(dom) {
//创建一个新的组件对象 并且通过mount将dom挂载到$el上
const newTest = new TestTemplate().$mount()
/* !现在newTest已经是一整个组件了 */
dom.appendChild(newTest.$el)
//01.还可以直接调用组件的方法
newTest.show()
//02.还可以删除dom
setTimeout(() => {
newTest.$el.remove()
}, 1000)
}