1

I am new to Vue, i want to create some buttons from my data and display their information when clicking the button. The object 'pets' has two keys: id and info. (My data is larger and my code more complicated, i was trying to simplify it here.)

data() {
  return {
    selectedpet: undefined,
    message: undefined,
    pets : [
      {
        id: 1,
        info: "yellow"
      },
      {
        id: 2,
        info: "brown"
      },
      {
        id: 3,
        info:"huge"
      }
    ]
  }
}

And I created some buttons by the data with the 'id' displayed on the buttons, and the variable 'selectedpet' will record the clicked button:

<div v-for="pet in pets :key="pet.id">
<button @click="selectedpet = pet">
    <i>{{pet.id}}</i>
</button>  

What i need to do is to create a div, which text will display the 'info' of the clicked button. How can i set the message to the 'info' of the click button?

<div id="printselectedpet">Selected pet: {{ message }}</div>

3 Answers 3

2

No need for message data

<div id="printselectedpet">Selected pet: {{ selectedpet.info }}</div>
Sign up to request clarification or add additional context in comments.

Comments

2

I think you just need to set pet.info to message.

See below code:

var vm = new Vue({
  el : "#vueRoot",
  data: {
    selectedpet: undefined,
    message: undefined,
    pets : [
      {
        id: 1,
        info: "yellow"
      },
      {
        id: 2,
        info: "brown"
      },
      {
        id: 3,
        info:"huge"
      }
    ]
	}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="vueRoot">
  <div v-for="pet in pets" :key="pet.id">
    <button @click="message = pet.info">
        <i>{{pet.id}}</i>
    </button>
  </div>
  <div id="printselectedpet" v-if="message">Selected pet: {{ message }}</div>
</div>

Comments

1

Below is my solution

new Vue({
el:"#app",

data:{
message:"I am initial message",
buttonz:[{id:1,info:"this is first button"},{id:2,info:"this is secoind button"},{id:3,info:"this is my third button"}]
},
methods:{
getMyKey(myKey){
if(myKey != undefined){
this.message = this.buttonz[myKey].info;
}else{
this.message = "Cannot Get the Key";

}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<div>
{{message}}
</div>
<button v-for="(but,index) in buttonz" :key="but.id" @click="getMyKey(index)">
My ID: {{but.id}}
</button>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.