簡體   English   中英

有沒有辦法縮短定義 v-model 數據、Vue.js 和 Laravel

[英]Is there a way to shorten defining v-model data, Vue.js and Laravel

在我的 CRUD 項目的編輯頁面上,我有一個代碼,用正在編輯的記錄的值填充表單。
我使用v-model來定義 HTML 輸入,但是代碼似乎太長了。
我從道具中獲取數據,並填充v-model

我的填充 v-model 的代碼

created() {
            this.studentData = this.student;
            this.first_name = this.student.first_name;
            this.last_name = this.student.last_name;
            this.student_number = this.student.last_name;
            this.phone_number = this.student.phone_number;
            this.email = this.student.email;
            this.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
            this.school_name = this.student.school_name;
        }

我使用 prop: props: ['student']和刀片<student-edit-component :student="{{$student}}">獲取數據的方式

在腳本中定義 v-model

data () {
            return {
                first_name: '',
                last_name: '',
                student_number: '',
                phone_number: '',
                email: '',
                birth_date: '',
                school_name: '',
            };
        },

這會用它的數據填充表單輸入上的值。

有沒有辦法使用道具或數組來縮短這段代碼?

請幫助我,我對Vue很陌生

您可以更改數據模型添加新層。 例如:

  data() {
    return {
      currentStudent: {
        first_name: '',
        last_name: '',
        student_number: '',
        phone_number: '',
        email: '',
        birth_date: '',
        school_name: '',
      }
    }
  },

然后在created你可以使用簡單

  created() {
    this.currentStudent = this.student;
    this.currentStudent.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
  },

並在所有組件中用currentStudne的名稱替換名稱,例如在v-models中:

first_name -> currentStudne.first_name

您還可以閱讀有關Vue.$set

https://v2.vuejs.org/v2/guide/reactivity.html

您可以使用對象studentData ,它適用於v-model 首先,你像這樣傳遞道具:

<student-edit-component :student="student"> (無需使用${{}} )。

然后在組件`StudentEditComponent'中,你可以使用:

props: {
    student: {
        type: Object,
        required: true,
        default : () => {},
    }
}

您應該使用 type、required 和 default 屬性,這是一個很好的做法。 然后

data () {
        return {
            studentForm: {},
        };
    },

created() {
        this.studentForm = this.student;
    }

在模板中,之后您可以使用v-model="studentForm.first_name"

暫無
暫無

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

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