vue——@component——继承 的一些知识点

本文探讨了在Vue中使用@Component注解时,如何处理this绑定,特别是涉及父子组件继承的情况。当父类未使用注解,this可能为undefined,需要通过不传递参数或在事件处理函数中传递$event来正确访问。而当父类使用@Component后,子类不能通过super.created()继承,会导致错误。同时,文章展示了具体的代码示例,揭示了Vue中组件继承和this访问的微妙之处。

2021年7月29日

  • 没有写注解(@component ):
    • 父类没有写注解 那么父类的函数的 this 绑定会找不到地方,此时 this是 undefined。如果想绑定 this 成功,有两种情况:
      //1 不传递参数
      <span @click="fn">-</span> // HTML
      fn(){ console.log(this.name) } // JS
      
      //2 传参的时候参数写全,写上$event
      <span @click="fn($event)">-</span> // HTML
      fn( key ){ console.log(this.name, key) } // JS
  • 写了注解:
    • 这时候 this 随便访问,但是字类不可以用 super.created()来继承了。继承的话会报错,call函数无法访问

---------------以下是 原文-----------------

vue的@component的学习

背景:

有一次要用到继承来写,继承里面又涉及到 super.created() 的访问,然后又涉及到在父类访问 this.$store 和 this.属性 ... 这些都出问题了 ,报错信息写在

情况:

祖父类:

import components1 from '@/components';
import { Component, Vue } from 'vue-property-decorator';

@Component({
	components: { components1 },
})
export class GrandFather extends Vue {
	attr1 = false;
	attr2 = false;

	static f1: () => void;

	static f4: () => void;
}

父类:

// @Component 如果不注释掉,子类继承的时候调用super 会报错,详细见子类 🧡
export default class Father extends GrandFather {
    attr3='x'
	getList() {}

	created() {
		this.getList(); //⭐ 可以访问
	}

	// handle1({ item, key }) {
	// 	 this.$store.commit(AAA, { // ⭐ this → undefined
	//		 a1: this.attr1, //⭐ this → undefined
	//		 a2:  key
	//	 });
	// }

	handle1(e) {
		e.item.$store.commit(AAA, { 
			a1: e.item.$route.name.slice(3),  // 这是取巧
			a2: e.key
		});
	}
}

/*  我不知道为什么啊 ┭┮﹏┭┮,为什么穿了参数的函数就访问不了本类的 this,
 没传参数的就可以访问本类的this */

子类 

import * as api from '@/api/index';
import { Component } from 'vue-property-decorator';
import Father from '../index.calss';

@Component
export default class extends Father {
	list = [];

	created() {
		super.created(); //🧡  Cannot read property 'call' of undefined
	}

	getList() {
		api.getTableList(params)
			.then((data) => {
				this.list = data.data
			})
			.catch(() => {});
	}
}

参考:

vue-ts中的@Component 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值