简体   繁体   中英

passing user input to another component in vue.js

I'm fairly new to vue.js but I couldn't seem to find a concrete answer for what I'm looking for but I also am new enough that I might have been looking right at the answer and not known it. So.

What I'm trying to do is create a 1 page application that tracks turns basically. It will:

  1. takes user input on how many users are participating
  2. ask for the names of all the users
  3. use the names which I currently have saved in an array, to build user cards, just showing the name of each user.
  4. You will click your name when your turn is over and the next persons card/button will 'raise' and then they click it, etc.

I'm currently having a hard time with that 3rd part. I need to figure out how I can pass this array of users to my other component's data object so I can use vue.js to loop and just spit the cards out.

initial-start.vue - template

<template lang="html">
 <div>
  <div>
   <h1>How many users?</h1>
   <input type="number" id="myNumber" value="0">
   <button v-on:click="getUsers">Submit</button>
   <app-area v-if="users > 0 && users < 5"></app-area>
  </div>
</div>
</template>

initial-start.vue - script

<script>
export default {
methods:{
getUsers(){
  var counter = 0;
  var users = [];
  var x = document.getElementById("myNumber").value;
  if (x <= 0){
    alert('Please choose a number greater than 0.');
  }else if(x > 4){
    alert('Maximum 4 users!');
  }else{
    alert('thank you for that.')
  }
    while(counter < x){
      name = prompt('Please enter your names.');
      users.push(name);
      counter++;
    }
    return users;
  }
}
}
</script>  

app-area.vue - template

<template lang="html">
 <div>
  <h1>Turn: {{ turn }}</h1>
  <userCards></userCards>
 </div>
</template>

app-area.vue - script

<script>
 export default {
  data() {
   return{
    turn: 0,
    users: []
   }
  },
props: ['users']
}
</script>

The question is, "How do I get the array from the getUsers() function, into the app area where I would be able to loop like

<userCards v-for="user in users"></userCards>

and have a card/button for each person entered ?"

You should save the value of getUser in your data, and then you can pass that to your app-area component.

data: {
  users: 0
}
methods:{
getUsers(){
  @users = 2;
}

And then in your html:

<app-area v-if="users > 0 && users < 5" v-bind:users="users"></app-area>

Now your app-area template has access to users . So you can pass each user to userCard component

<userCards v-for="user in users" v-bind:user="user"></userCards>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM