const weather = { data() { return { date: (new Date).toLocaleString(), city: [ {…
- User
const weather = { data() { return { date: (new Date).toLocaleString(), city: [ { cityName: 'Macau', temperature: 28, condition: 'cloudy' }, { cityName: 'Beijing', temperature: 27, condition: 'sunny' }, { cityName: 'Shanghai', temperature: 34, condition: 'rainy' } ], newEntry: { cityName: '', temperature: undefined, condition: undefined } } }, methods: { startClock() { setInterval(() => { this.date = new Date().toLocaleString(); }, 1000); },
getConditionImage(cond) { return `./image/${cond}.png` }, addToCityTable(e) { // clone the object 'this.newEntry', and append the clone to the 'city' array this.city.push( {...this.newEntry} ); // clear the content of the input form this.newEntry = { cityName: '', temperature: undefined, condition: undefined }; }} }
why the date will not update sec by sec?
- Assistant
The reason the date is not updating every second is that the
startClock()method is defined but never called. In your Vue.js component, methods likestartClock()need to be invoked to perform their actions. Simply defining the method doesn't execute it.To fix this, you should call
startClock()when your component is created or mounted. In Vue.js, there are lifecycle hooks likecreated()andmounted()where you can place code that should run when the component is initialized. Here's how you can modify your code:const weather = { data() { return { date: (new Date).toLocaleString(), city: [ { cityName: 'Macau', temperature: 28, condition: 'cloudy' }, { cityName: 'Beijing', temperature: 27, condition: 'sunny' }, { cityName: 'Shanghai', temperature: 34, condition: 'rainy' } ], newEntry: { cityName: '', temperature: undefined, condition: undefined } }; }, methods: { startClock() { setInterval(() => { this.date = new Date().toLocaleString(); }, 1000); }, getConditionImage(cond) { return `./image/${cond}.png`; }, addToCityTable(e) { this.city.push({ ...this.newEntry }); this.newEntry = { cityName: '', temperature: undefined, condition: undefined }; } }, mounted() { this.startClock(); // Call startClock when the component is mounted } };