如果您有附加了点击事件的项目列表,那么如何使用Vue.js(2.0)对单击的子元素应用特定更改?这是一个例子:
HTML:
<div id="root">
<div class="selection">
<div class="option" v-for="option in options" @click="processSelection(option)">
<p class="text">{{ option.text }}</p>
<p class="feedback"></p>
</div>
</div>
</div>
使用Javascript:
new Vue({
el: '#root',
data: {
options: [
{ text: 'First option', feedback: 'First option feedback' },
{ text: 'Second option', feedback: 'Second option feedback' },
{ text: 'Third option', feedback: 'Third option feedback' },
{ text: 'Fourth option', feedback: 'Fourth option feedback' },
]
},
methods: {
processSelection(option) {
alert(option.text + ' was clicked');
//Update the respective feedback div
//...
}
}
});
这样就会显示一个项目列表。当您单击第三个项目时,如何使用相关反馈文本更新相应的.feedback
块?这是JS Bin中的代码:https://jsbin.com/ricewuf/edit?html,js,output
答案 0 :(得分:3)
我认为您可以在选项对象上添加另一个布尔属性,例如showFeedback,然后只需更改其值以显示反馈!
最好在代码中显示:)
JS
https://jsbin.com/diquwemiti/edit?html,js,output
new Vue({
el: '#root',
data: {
options: [
{ text: 'First option', feedback: 'First option feedback', showFeedback: false},
{ text: 'Second option', feedback: 'Second option feedback', showFeedback: false },
{ text: 'Third option', feedback: 'Third option feedback', showFeedback: false },
{ text: 'Fourth option', feedback: 'Fourth option feedback', showFeedback: false },
]
},
methods: {
processSelection(option) {
option.showFeedback = true
}
}
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="root">
<div class="selection">
<div class="option" v-for="option in options" @click="processSelection(option)">
<p class="text">{{ option.text }}</p>
<p class="feedback" v-if="option.showFeedback">{{ option.feedback }}</p>
</div>
</div>
</div>
</body>
</html>
答案 1 :(得分:0)
您仍然可以将原始事件传递给事件处理程序并使用它来查找.feedback
div:
new Vue({
el: '#root',
data: {
options: [{
text: 'First option',
feedback: 'First option feedback'
}, {
text: 'Second option',
feedback: 'Second option feedback'
}, {
text: 'Third option',
feedback: 'Third option feedback'
}, {
text: 'Fourth option',
feedback: 'Fourth option feedback'
}, ]
},
methods: {
processSelection(option, e) {
var target = e.currentTarget;
var feedback = target.querySelector('.feedback');
feedback.innerHTML = option.feedback;
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js">
</script>
<div id="root">
<div class="selection">
<div class="option" v-for="option in options" @click="processSelection(option, $event)">
<p class="text">{{ option.text }}</p>
<p class="feedback"></p>
</div>
</div>
</div>
&#13;
以下是有关此问题的一些文档:https://vuejs.org/v2/guide/events.html#Methods-in-Inline-Handlers