8. Vue methods和computed中不能使用箭头函数

Vue methods和computed中不能使用箭头函数

  • 概述

    在 Vue 的 methodscomputed 中不能使用箭头函数,箭头函数中的 this 会指向 windows 而非 Vue 的实例。

  • 示例

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Vue methods和computed中不能使用箭头函数</title>
    </head>
    <body>
    	<div id="app">
    		<h2>使用箭头函数</h2>
    		<button @click="method_1">使用箭头函数回调</button>
    		<p>name: {{ computed_1 }}</p>
    		<h2>不使用箭头函数</h2>
    		<button @click="method_2">使用箭头函数回调</button>
    		<p>name: {{ computed_2 }}</p>
    	</div>
    	<!-- 开发环境版本,包含了有帮助的命令行警告 -->
    	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    	<script>
    		app = new Vue({
    			el: '#app',
    			data: {
    				name: 'data中的name变量'
    			},
    			methods: {
    				method_1: () => {
    					this.name = 'method_1函数设置的属性'
    					console.log('method_1:'+this)  // this 指向的是windows
    				},
    				method_2() {
    					this.name = 'method_2函数设置的属性'
    					console.log('method_2:'+this)  // this 指向的是Vue实例
    				}
    			},
    			computed: {
    				computed_1: () => {
    					console.log('computed_1:'+this)  // this 指向的是windows
    					return this.name
    				},
    				computed_2() {
    					console.log('computed_2:'+this)  // this 指向的是Vue实例
    					return this.name
    				}
    			}
    		})
    	</script>
    </body>
    </html>
    
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值