• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

279
Views
Restablecer a los datos iniciales en vuejs, pero solo para algunos de los valores

El siguiente código para un componente vuejs establece con éxito el estado inicial de los datos para el nombre del jugador, la hora y los errores. Extraer los datos iniciales a una función me permite restablecer fácilmente los datos al estado inicial.

Genial... pero... solo quiero que el tiempo y el error se restablezcan al estado inicial y quiero que el nombre del jugador continúe.

¿Hay una forma recomendada de lograr esto? Parece que solo puedo encontrar enfoques de todo o nada o un enfoque torpe para restablecer manualmente que requerirá que recuerde si cambio en el futuro.

Agradezco su mirada y cualquier ayuda.

 function initialState (){ return { playerName: '', time: 0, errors: 0 } } //In my component: data: function (){ return initialState(); } //Call this method when I want to start over methods:{ reset: function (){ Object.assign(this.$data, initialState()); } }
about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede tomar el estado inicial y volver a fusionar sus guardianes con él antes de reasignarlos así con una combinación en línea súper abreviada:

 export default { data: () => ({ playerName: '', time: 0, errors: 0 }) methods: { reset () { const playerName = ...this.playerName; // Use Spread (...) to clone this.playerName so we don't assign a reactive copy that becomes blank again. return Object.assign(this.$data, { ...this.$options.data(), playerName }) } } }

La combinación en línea { ...this.$options.data(), playerName } es una característica de ES6, la inyección de playerName es lo mismo que escribir:

 { ...this.$options.data(), playerName: ...this.playerName }

¿Qué está haciendo this.$options.data() ?

 { ...{ playerName: '', time: 0, errors: 0 }, playerName: ...this.playerName },

Los tres puntos se denominan Sintaxis extendida , básicamente se trata de fusionar el objeto data en nuestro nuevo {} objeto vacío y luego sobrescribir los atributos después de la inyección.

Este total es el equivalente a escribir:

 Object.assign(this.$data, () => { const data = { playerName: '', time: 0, errors: 0 } data.playerName = ...this.playerName return data }())
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error