Vue组件的继承用法示例详解
作者:mochenxiya 时间:2024-05-29 22:44:22
Vue组件的继承用法
vue组件的继承适用于UI几乎一样,只是数据不一样的情况下,但是这种情况通过统一封装组件也是能实现的,小功能建议用封装,大功能建议用组件继承,因为大功能在结合搜参数的需要多重的判断,这样会导致封装的组件比较繁杂,出现过多的判断,用继承可以改写基类中的方法和数据
基类案例:
<template>
<div class="hello">
父类:{{name}}
<span>{{title}}</span>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return{
name:'末晨曦吖',
title:'Vue组件的继承用法'
}
},
mounted(){
console.log('父组件',this.name);
},
methods:{
handle(){
console.log('我是父组件方法');
}
}
}
</script>
<style scoped>
</style>
继承基类案例:
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
extends:HelloWorld,
data(){
return {
}
},
mounted() {
console.log("子类继承父组件name", this.name);
this.handle()
// this.title = '子组件更改了title'
},
components:{
},
methods:{
}
}
</script>
<style scoped>
</style>
效果:
可以看见,不改写基类的时候,继承了父类的所有东西,当前的data,dom,方法都继承了
改写父类案例:
<template>
<div id="app">
子组件:{{name}}
<span>{{title}}</span>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
extends:HelloWorld,
data(){
return {
}
},
mounted() {
console.log("子类继承父组件name", this.name);
this.handle()
this.name = '子组件更改了name'
this.title = '子组件更改了title'
},
components:{
},
methods:{
handle(){
console.log('子组件改写方法');
}
}
}
</script>
<style scoped>
</style>
效果:
我们会发现,改写后基类的值也被覆写了,方法也被覆写了,html模板也完全被改写了
HTML模板要么完全继承,要么完全重写,不能按需继承某个部分。如果子类在结构上跟基类有所差异,还是需要在基类中做条件判断。如果模板差异太大,可以重新定义子类自己的template,至少还可以重用一部分业务逻辑代码。
来源:https://www.cnblogs.com/mochenxiya/archive/2022/08/16/16593312.html
标签:Vue,组件,继承
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python基本数据类型详细介绍
2021-10-14 07:02:50
sql 2000清空后让表的id从1开始等数据库操作
2024-01-18 11:30:15
异步完成后新开窗口
2010-04-06 12:37:00
php集成环境xampp中apache无法启动问题解决方案
2023-07-17 22:44:52
![](https://img.aspxhome.com/file/2023/8/55478_0s.png)
Python实现实时跟随微信窗口移动的GUI界面
2022-06-09 11:12:25
![](https://img.aspxhome.com/file/2023/4/103494_0s.gif)
python np.arange 步长0.1的问题需要特别注意
2021-09-26 08:49:49
![](https://img.aspxhome.com/file/2023/4/118784_0s.png)
利用Python实现在同一网络中的本地文件共享方法
2023-10-31 00:41:58
JavaScript简单编程实例学习
2024-04-29 13:24:52
Python写出新冠状病毒确诊人数地图的方法
2022-09-28 06:15:13
![](https://img.aspxhome.com/file/2023/3/133433_0s.png)
Ubuntu下安装卸载python3.8的过程
2021-09-06 10:43:28
谈ASP的未来
2009-03-24 20:35:00
MySQL 自动清理binlog日志的方法
2024-01-17 11:37:59
基于Python 函数和方法的区别说明
2023-10-03 02:04:01
pytorch之torchvision.transforms图像变换实例
2021-05-19 05:44:05
在Pycharm中对代码进行注释和缩进的方法详解
2023-09-27 23:55:26
Django 中使用日志的方法
2022-09-12 11:17:40
![](https://img.aspxhome.com/file/2023/3/101453_0s.png)
pywinauto自动化操作记事本
2021-07-19 03:01:57
python 中的 return 解析
2023-11-03 13:21:47
一次Mysql使用IN大数据量的优化记录
2024-01-29 07:49:19
![](https://img.aspxhome.com/file/2023/8/93898_0s.png)
源码编译安装MySQL8.0.20的详细教程
2024-01-22 11:55:52
![](https://img.aspxhome.com/file/2023/5/101355_0s.png)