vue动态渲染@click点击事件

vue动态渲染@click点击事件

一般情况下当我们要写动态点击事件一开始的想法都是这样子的 (错误写法)

大致的伪代码 – 错误写法

// 数据部分
tests = [
	{
    
    
		method: test1
	},
	{
    
    
		method: test2
	},
	{
    
    
		method: test4
	},
]
//方法部分
test1() {
    
    
	//输出
},
test2() {
    
    
	//输出
},
test3() {
    
    
	//输出
}
<div v-for="test in this.tests "> 
	<随便一个要按的 @click="test.method"></随便一个要按的>
</div>

错误原因:

因为我们循环的时候@click="test.method 
会变成 @click="'test1'" ,@click="'test2'",@click="'test3'"

正确写法:

  1. 假定一个方法名,然后传入的参数进行改变

例子:

<div v-for="test in this.tests "> 
	<随便一个要按的 @click="ttt(test.method)"></随便一个要按的>
</div>
ttt(method) {
    
    
	if(method === 'test1') {
    
    
		//输出
	}else if(method === 'test2') {
    
    
		//输出
	}else if(method === 'test3') {
    
    
		//输出
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42947972/article/details/125307916
今日推荐