有什么方法可以在vuejs中的同一数据对象中使用data属性?

问题描述 投票:0回答:1

我是Vue js和前端框架的初学者。最近,我了解了vue js。所以我在vue js中有一个小任务。简单添加用户并显示我添加的所有用户。这是我的代码。

<div id="todo">
    <b-card class="col-md-12 text-center">
      <b-row>
        <b-col md="4">
          <b-input v-model="firstName" placeholder="Firstname"></b-input>
        </b-col>
        <b-col md="4">
          <b-input v-model="lastName" placeholder="Lastname"></b-input>
        </b-col>
        <b-col md="2">
          <b-btn class="btn btn-success" @click="addUser">Add User</b-btn>
        </b-col>
      </b-row>
    </b-card>
    <table>
      <caption>Users</caption>
      <thead>
        <tr>
          <th>Index</th>
          <th>First name</th>
          <th>Last name</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(u, index) in users" :key="index">
          <td>{{u.uid}}</td>
          <td>{{u.firstname}}</td>
          <td>{{u.lastname}}</td>
        </tr>
      </tbody>
    </table>
  </div>

<script>
export default {
  name: "todo",
  data() {
    return {
      users: [{ id: **this.uid**, firstname: "John", lastname: "Doe" }],
      **uid**: 1,
      firstName: "",
      lastName: ""
    };
  },
  methods: {
    addUser() {
      let newUser = {
        id: this.id + 1,
        firstname: this.firstName,
        lastname: this.lastName
      };
      this.users.push(newUser);
      (this.firstName = ""), (this.lastName = "");
    }
  }
};
</script>

现在,我的问题是可以在数据对象的用户数组中使用uid吗?

vuejs2
1个回答
0
投票

您可以按照以下方法在created方法中运行代码

{
   created () {
      let firstUser = { id: this.uid, firstname: "John", lastname: "Doe" }
      this.users.push(firstUser)
   },
   data () {
      users: [],
      uid: 1
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.