我有一个内部有3个对象的数组。每个对象都有4个属性:
buttons: [
{
id: 'btn1',
name: 'button-1',
number: 1,
color: 'red'
},
{
id: 'btn2',
name: 'button-2',
number: 2,
color: 'blue'
},
{
id: 'btn3',
name: 'button-3',
number: 3,
color: 'orange'
}
]
在我的html中,我有3个按钮,每个按钮都连接到给定的对象。
<button id="btn1" name="" number="" color="">One</button>
<button id="btn2" name="" number="" color="">Two</button>
<button id="btn3" name="" number="" color="">Two</button>
<hr>
<h2>Clicked button data:</h2>
<p>{{ id }}</p>
<p>{{ name }}</p>
<p>{{ number }}</p>
<p>{{ color }}</p>
如何基于单击的按钮显示给定对象的数据?
以下是我的代码段:
答案 0 :(得分:2)
这很简单。您只需要附加一个带有@
前缀的事件侦听器即可。该侦听器必须是在vue对象上methods
对象中定义的方法。然后,您可以让该方法接收按钮对象作为参数。在我的示例中,我添加了一个由方法设置的当前属性,该属性包含最后按下的按钮。我还用一个输入和一个v-for
指令替换了这四个按钮,但它也适用于按钮。
var app = new Vue({
el: '#app',
data: {
buttons: [{
id: 'btn1',
name: 'button-1',
number: 1,
color: 'red'
},
{
id: 'btn2',
name: 'button-2',
number: 2,
color: 'blue'
},
{
id: 'btn3',
name: 'button-3',
number: 3,
color: 'orange'
}
],
current: {}
},
methods: {
setCurrent(btn) {
this.current = btn;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="button" v-for="btn in buttons" :id="btn.id" @click="setCurrent(btn)" :value="btn.name">
<p>{{ current.id }}</p>
<p>{{ current.name }}</p>
<p>{{ current.number }}</p>
<p>{{ current.color }}</p>
</div>
答案 1 :(得分:1)
对于按钮:
<button id="btn1" name="" number="" color="" @click="set_SelectedButton(1)">One</button>
在方法中:
set_SelectedButton(value){
// or Based on condition how every you want
this.btn_id="value"
}
<h2>Clicked button data:</h2>
<p>{{ button[btn_id].id }}</p>
<p>{{ button[btn_id].name }}</p>
<p>{{ button[btn_id].number }}</p>
<p>{{ button[btn_id].color }}</p>
答案 2 :(得分:0)
您只需要根据按钮编号创建一个功能。
<button id="btn1" name="" number="" color=""
@click = "clickedOn(1)">One</button>
<button id="btn2" name="" number="" color=""
@click = "clickedOn(2)">Two</button>
<button id="btn3" name="" number="" color=""
@click = "clickedOn(3)">Three</button>
<hr>
<h2>Clicked button data:</h2>
<p>{{ dataToShow.id }}</p>
<p>{{ dataToShow.name }}</p>
<p>{{ dataToShow.number }}</p>
<p>{{ dataToShow.color }}</p>
</div>
您可以在此处查看工作示例: https://jsfiddle.net/nud19tfz/
var app = new Vue({
el: '#app',
data: {
buttons: [
{
id: 'btn1',
name: 'button-1',
number: 1,
color: 'red'
},
{
id: 'btn2',
name: 'button-2',
number: 2,
color: 'blue'
},
{
id: 'btn3',
name: 'button-3',
number: 3,
color: 'orange'
}
],
dataToShow: {}
},
methods: {
clickedOn: function(btnNum) {
this.dataToShow = this.buttons[btnNum-1]
}
}
});