Search code examples
vue.jsvuexstore

I want to display an arbitrary value from the state array stored in the store.js file


enter image description here

User information is managed by the state of the store.js file.

User information is managed by the state of the store.js file.

const store = createStore({
  state() {
    return {
      users:[
        {id: 0, userName: 'test1', wallet: 500},
        {id: 1, userName: 'test2', wallet: 1000},
        {id: 2, userName: 'test3', wallet: 1500},
        {id: 3, userName: 'test4', wallet: 2000},
      ],
      userName: '',
      updateUserName: '',
      userLoginInfomation: '',
      errorMessage: ''
    };
  },

A modal is displayed when you press the button to view the wallet.

↓The modal that appears when you click View Wallet.

    <div class="overlay" v-show="showContent" @click="closeModal">
      <transition name="modal">
        <div v-show="showContent" class="content">
          <p>{{ viewUsers[1].userName }} balance</p>
          <p>{{ viewUsers[1].wallet }}yen</p>
          <p>
            <button class="close-button" @click="closeModal">Close</button>
          </p>
        </div>
      </transition>
    </div>

↓The modal that appears when you click send.

<div class="overlay" v-show="showContent2" @click="closeModal">
      <div class="content">
        <p> Your balance:500yen</p>
        <p>Amount to send</p>
        <input type="text" class />
        <p>
          <button class="close-button" @click="closeModal2">Close</button>
        </p>
      </div>
    </div>

What you want to achieve

(1) When you click the View Wallet button, you want to get the user name with the same index number as the clicked index number from state.users in the store.js file and display it modally.

(2) When you click the send button, enter the amount to send to the displayed modal input. I want to add the amount of money entered in the wallet of the state.users data of the store.js file that has the same sequence number as the clicked button.


Solution

  • This is untested, but should help you get in the right direction:

    <template>
      <ul>
        <li v-for="user in users" :key="user.id" @click="selectUser(user)">
          {{ user.userName }} | {{ user.wallet }}
        </li>
      </ul>
    
      <div class="modal" v-if="showModal">
        <!-- 
        here you can now access whatever user properties
        you want via the selectedUser property
        -->
    
        <p>Name: {{ selectedUser.userName }}</p>
        <p>ID: {{ selectedUser.id }}</p>
        <p>Wallet: {{ selectedUser.wallet }}</p>
      </div>
    </template>
    
    <script>
      data: () => ({
        selectedUser: null
      }),
    
      computed: {
        users() {
          return this.$store.users;
        }
      },
    
      methods: {
        selectUser(user) {
          this.selectedUser = user;
          this.showModal = true;
        }
      },
    </script>