vue @component继承的一些知识点详解

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