簡體   English   中英

如何在 VueJS 中傳遞道具?

[英]How to pass props in VueJS?

我的應用程序中有一個簡單的設置,它由 2 個組件組成。 HelloWorld 組件,然后是對話框組件。 對話框組件接受從 HelloWorld 組件傳遞的props HelloWorld 中的數據是通過遍歷數組來呈現的。 我想要實現的是,當我單擊其中一個元素時,我希望對話框中預先填充我單擊的元素的名稱和年齡。 我不確定我該怎么做?

查看此CodeSandbox以了解完整的設置。

這是我的 Vuex 商店:-

state: {
    userData: [
      {
        name: "Sam",
        age: "24"
      },
      {
        name: "Max",
        age: "28"
      }
    ],
    dialog: false
  },
  getters: {
    getUserData: state => state.userData,
    getDialog: state => state.dialog
  },
  mutations: {
    openDialog(state) {
      state.dialog = true;
    }
  }

這是我的 HelloWorld 組件:-

<template>
  <v-container>
    <v-layout justify-center>
      <v-card>
        <v-card-text>
          <div v-for="user in getUserData" :key="user.age">
            <span>{{user.name}}</span>
            <span>{{user.age}}</span>
            <v-icon @click="openDialog">create</v-icon>
          </div>
        </v-card-text>
      </v-card>
    </v-layout>
    <Dialog/>
  </v-container>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import Dialog from "./Dialog";
export default {
  name: "HelloWorld",
  components: {
    Dialog
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getUserData: "getUserData"
    })
  },
  methods: {
    ...mapMutations({
      openDialog: "openDialog"
    })
  }
};
</script>

這是我的對話框組件:-

<template>
  <v-dialog v-model="getDialog" max-width="300px">
    <v-card>
      <v-card-text>
        <v-text-field v-model="title"></v-text-field>
        <div class="mt-5">{{age}}</div>
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  props: {
    title: {
      type: String
    },
    age: {
      type: Number
    }
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getDialog: "getDialog"
    })
  }
};
</script>

感謝所有的幫助。 謝謝你。

<div v-for="(user, index) in getUserData" :key="user.age">
        <span>{{user.name}}</span>
        <span>{{user.age}}</span>
        <v-icon @click="openDialogAndGetCurrentUser(index)">create</v-icon>
 </div>
openDialogAndGetCurrentUser(index) {
   this.openDialog();
   /* define these in your data to be passed to child */
   this.currentuserName = this.getUserData[index].name;
   this.currentuserAge = this.getUserData[index].age;
}
<Dialog 
  :title="currentuserName"
  :age="currentuserAge"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM