this scope of uni

Table of contents

  • 01. Let's look at a case first
  • 02. Take a look at the solution

01. Let's look at a case first

  • The code is as follows
    • It is found that clicking button 1 can update the title content, but clicking button 2 cannot update the title content. Why on earth is this?
    <template>
    	<view class="container">
    		<text>{{title}}</text>
    		<button type="default" @click="changeTitle1">Change title content button 1</button>
    		<button type="default" @click="changeTitle2">Change title content button 2</button>
    	</view>
    </template>
    
    <script>
    	export default{
    		data(){
    			return{
    				title : "This is the title",
    			}
    		},
    		methods:{
    			changeTitle1(){
    				this.title = "Change Title 1";
    			},
    			//You can see that the following one executes the success method, but the content cannot be changed by calling this assignment
    			changeTitle2(){
    				uni.setStorage({
    				    key: 'storage_key',
    				    data: 'hello',
    				    success: function () {
    						this.title = "Change Title 2";
    				        console.log('changeTitle2------success');
    				    }
    				});
    			},
    		}
    	}
    </script>
    
    <style>
    	.container{
    		display: flex;
    		flex-flow: column;
    	}
    </style>
    
  • Why can't changeTitle2 change the title content
    • In the success method of the changeTitle2 method, the success method points to the closure, so this belongs to the closure, so this.title cannot be used directly in the success callback function.

02. Take a look at the solution

  • It can be found that this operation can solve the scope problem
  • First solution
    • The solution is to assign this to another variable outside the closure
    //It can be found that this operation can solve the scope problem
    changeTitle3(){
    	//assignment
    	var me = this;
    	uni.setStorage({
    	    key: 'storage_key',
    	    data: 'hello',
    	    success: function () {
    			me.title = "Change title 3";
    	        console.log('changeTitle2------success');
    	    }
    	});
    },
    
  • Second solution
    • You can also solve this problem by using the arrow function. Think about why?
    changeTitle4(){
    	uni.setStorage({
    	    key: 'storage_key',
    	    data: 'hello',
    	    success:() => {
    			this.title = "Change title 4";
    	        console.log('changeTitle2------success');
    	    }
    	});
    },
    

Tags: Front-end

Posted on Mon, 18 May 2020 10:27:52 -0400 by donbueck