Vue中运用ajax this指向问题

在vue component中的methods域里定义一个方法,这个方法中会调用某一个ajax call,在ajax中的this会指向ajax本身,而不再是vue实例本身。

methods: {
typeAhead: function (searchType) {
			**var self = this;** //获取vue实例本身,捕获指针指向
			var searchURL = "";
			switch (searchType) {
				case "companyName" :
					searchURL = "/my-account/typeAheadCompanyName";
					break;
				case "repId" :
					searchURL = "/my-account/typeAheadRepId";
					break;
				case "repFirstName" :
					searchURL = "/my-account/typeAheadRepFirstName";
					break;
				case "repLastName" :
					searchURL = "/my-account/typeAheadRepLastName";
					break;
			}
		
			var ajaxData = {};
			if(searchType == "companyName" || searchType == "repId") {
				ajaxData = {searchKeyWords:this.searchVal};
			}
			else {
				ajaxData = {repFirstName: this.firstName,repLastName: this.lastName}
			}
			$.ajax({
				type : "GET",
				url : searchURL,
				data : ajaxData,
				success : function(result) {
					**self.typeAheadResult.length=0;** //清空vue实例data中的数组
					for(var i=0;i

不要直接用this

你可能感兴趣的:(前端开发基础概念)