如何使用最新版本从Firebase编辑日期和时间选择器Vuejs Vuetify

时间:2018-11-27 08:14:36

标签: firebase vue.js vuetify.js

您好,我是vuejs和vuetify的新手,今天和几个星期前,我正在学习如何使用vuejs,vuetify和Firebase作为存储数据来创建项目。我的项目引用了以下链接:https://www.youtube.com/watch?v=FXY1UyQfSFw&list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt,并且仍在进行中,现在我的项目陷入了困境,下面是我所有代码的全部内容:

  

components文件夹components / Meetup / EditMeetupDateDioalog.vue

<template>
  <v-flex xs12 sm6 md4>
      <v-dialog
        v-model="editDialog"
        persistent
        lazy
        full-width
        width="290px"
      >
        <v-btn slot="activator" flat outline small color="primary">Edit date</v-btn>
        <v-date-picker v-model="editableDate" scrollable>
          <v-spacer></v-spacer>
          <v-btn flat color="primary" @click="editDialog = false">Cancel</v-btn>
          <v-btn flat color="primary" @click.native="onSaveChanges">Save</v-btn>
        </v-date-picker>
      </v-dialog>
    </v-flex>
</template>
<script>
  export default {
    props: ['meetup'],
    data () {
      return {
        editDialog: false,
        editableDate: null
      }
    },
    methods: {
      onSaveChanges () {
        const newDate = new Date(this.meetup.date)
        const newDay = new Date(this.editableDate).getUTCDate()
        const newMonth = new Date(this.editableDate).getUTCMonth()
        const newYear = new Date(this.editableDate).getUTCFullYear()
        newDate.setUTCDate(newDay)
        newDate.setUTCMonth(newMonth)
        newDate.setUTCFullYear(newYear)
        this.$store.dispatch('updateMeetupData', {
          id: this.meetup.id,
          date: newDate
        })
      }
    },
    created () {
      this.editableDate = new Date(this.meetup.date)
    }
  }
</script>
  

main.js

import Vue from 'vue'
import App from './App'
import * as firebase from 'firebase'
import router from './router'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import { store } from './store'
import DateFilter from './filters/date'
import AlertCmp from './components/Shared/Alert.vue'
import EditMeetupDetailsDialog from './components/Meetup/Edit/EditMeetupDetailsDialog.vue'
import EditMeetupDateDialog from './components/Meetup/Edit/EditMeetupDateDialog.vue'
// import GMapAutocomplete from './components/Meetup/GMapAutocomplete.vue'

Vue.use(Vuetify, { theme: {
  primary: '#03a9f4',
  secondary: '#424242',
  accent: '#82B1FF',
  error: '#FF5252',
  info: '#2196F3',
  success: '#4CAF50',
  warning: '#FFC107'
}})

Vue.config.productionTip = false

Vue.filter('date', DateFilter)

Vue.component('app-alert', AlertCmp)

Vue.component('app-edit-meetup-details-dialog', EditMeetupDetailsDialog)

Vue.component('app-edit-meetup-date-dialog', EditMeetupDateDialog)

// Vue.component('app-gmap-autocomplete', GMapAutocomplete)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App),
  created () {
    firebase.initializeApp({
      apiKey: 'AIzaSyCd_0uXFwdV5s6NTqJyC*******',
      authDomain: 'kopdar-dev.firebaseapp.com',
      databaseURL: 'https://kopdar-dev.firebaseio.com',
      projectId: 'kopdar-dev',
      storageBucket: 'kopdar-dev.appspot.com'
    })
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.$store.dispatch('autoSignIn', user)
      }
    })
    this.$store.dispatch('loadedMeetups')
  }
})
  

store / index.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    loadedMeetups: [
      {
        imageUrl: 'http://www.all-free-photos.com/images/paris/IM2392-hr.jpg',
        id: 'kdgkyrjwlklnfhaifh25u92wrl',
        title: 'Meetup in Paris',
        date: new Date(),
        location: 'Paris - French',
        description: 'This meetup talk about modern web application'
      },
      {
        imageUrl: 'http://www.all-free-photos.com/images/berlin/PI88764-hr.jpg',
        id: 'sjgs8wjw0sklsgj90836skfnk',
        title: 'Meetup in Berlin',
        date: new Date(),
        location: 'Berlin - German',
        description: 'Talk about I/O modern web application'
      }
    ],
    user: null,
    loading: false,
    error: null
  },
  mutations: {
    setLoadedMeetups (state, payload) {
      state.loadedMeetups = payload
    },
    createMeetup (state, payload) {
      state.loadedMeetups.push(payload)
    },
    updateMeetup (state, payload) {
      const meetup = state.loadedMeetups.find(meetup => {
        return meetup.id === payload.id
      })
      if (payload.title) {
        meetup.title = payload.title
      }
      if (payload.description) {
        meetup.description = payload.description
      }
      if (payload.location) {
        meetup.location = payload.location
      }
      if (payload.date) {
        meetup.date = payload.date.toISOString
      }
    },
    setUser (state, payload) {
      state.user = payload
    },
    setLoading (state, payload) {
      state.loading = payload
    },
    setError (state, payload) {
      state.error = payload
    },
    clearError (state) {
      state.error = null
    }
  },
  actions: {
    loadedMeetups ({commit}) {
      commit('setLoading', true)
      firebase.database().ref('kopdar').once('value')
        .then(
          (data) => {
            const kopdar = []
            const obj = data.val()
            for (let key in obj) {
              kopdar.push({
                id: key,
                title: obj[key].title,
                location: obj[key].location,
                description: obj[key].description,
                imageUrl: obj[key].imageUrl,
                date: obj[key].date,
                creatorId: obj[key].creatorId
              })
            }
            commit('setLoadedMeetups', kopdar)
            commit('setLoading', false)
          }
        )
        .catch(
          (error) => {
            console.log(error)
            commit('setLoading', true)
          }
        )
    },
    createMeetup ({commit, getters}, payload) {
      const meetup = {
        title: payload.title,
        location: payload.location,
        description: payload.description,
        date: payload.date.toISOString(),
        creatorId: getters.user.id
      }
      let imageUrl
      let key
      firebase.database().ref('kopdar').push(meetup)
        .then((data) => {
          key = data.key
          return key
        })
        .then(key => {
          const filename = payload.image.name
          const ext = filename.slice(filename.lastIndexOf('.'))
          return firebase.storage().ref('kopdar/' + key + '.' + ext).put(payload.image)
        })
        .then(fileData => {
          // imageUrl = fileData.metadata.downloadURLs[0]
          // imageUrl = 'http://www.all-free-photos.com/images/paris/IM2392-hr.jpg'
          imageUrl = firebase.storage().ref(fileData.metadata.fullPath).getDownloadURL()
          .then((url) => {
            return firebase.database().ref('kopdar').child(key).update({imageUrl: url})
          })
          // return firebase.database().ref('kopdar').child(key).update({imageUrl: imageUrl})
        })
        .then(() => {
          commit('createMeetup', {
            ...meetup,
            imageUrl: imageUrl,
            id: key
          })
        })
        .catch((error) => {
          console.log(error)
        })
      // Reach out  to firebase and store it
    },
    updateMeetupData ({commit}, payload) {
      commit('setLoading', true)
      const updateObj = {}
      if (payload.title) {
        updateObj.title = payload.title
      }
      if (payload.description) {
        updateObj.description = payload.description
      }
      if (payload.location) {
        updateObj.location = payload.location
      }
      if (payload.date) {
        updateObj.date = payload.date.toISOString()
      }
      firebase.database().ref('kopdar').child(payload.id).update(updateObj)
      .then(() => {
        commit('setLoading', false)
        commit('updateMeetup', payload)
      })
      .catch(error => {
        console.log(error)
        commit('setloading', false)
      })
    },
    signUserUp ({commit}, payload) {
      commit('setLoading', true)
      commit('clearError')
      firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
        .then(
          user => {
            commit('setLoading', false)
            const newUser = {
              id: user.uid,
              registeredMeetups: []
            }
            commit('setUser', newUser)
          }
        )
        .catch(
          error => {
            commit('setLoading', false)
            commit('setError', error)
            console.log(error)
          }
        )
    },
    signUserIn ({commit}, payload) {
      commit('setLoading', true)
      commit('clearError')
      firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
        .then(
          user => {
            commit('setLoading', false)
            const newUser = {
              id: user.uid,
              registeredMeetups: []
            }
            commit('setUser', newUser)
          }
        )
        .catch(
          error => {
            commit('setLoading', false)
            commit('setError', error)
            console.log(error)
          }
        )
    },
    autoSignIn ({commit}, payload) {
      commit('setUser', {id: payload.uid, registeredMeetups: []})
    },
    logout ({commit}) {
      firebase.auth().signOut()
      commit('setUser', null)
    },
    clearError ({commit}) {
      commit('clearError')
    }
  },
  getters: {
    loadedMeetups (state) {
      return state.loadedMeetups.sort((meetupA, meetupB) => {
        return meetupA.date > meetupB.date
      })
    },
    featuredMeetups (state, getters) {
      return getters.loadedMeetups.slice(0, 5)
    },
    loadedMeetup (state) {
      return (meetupId) => {
        return state.loadedMeetups.find((meetup) => {
          return meetup.id === meetupId
        })
      }
    },
    user (state) {
      return state.user
    },
    loading (state) {
      return state.loading
    },
    error (state) {
      return state.error
    }
  }
})
  

我的Meetup.vue

<template>
    <v-container>
        <v-layout row wrap>
          <v-flex xs12 sm6 offset-sm3>
            <!-- <v-progress-circular
              :size="70"
              :width="7"
              color="primary"
              indeterminate
              v-if="loading"
              ></v-progress-circular> -->
            <!-- <div class="text-xs-center">
              <v-progress-circular
              :rotate="-90"
              :size="100"
              :width="15"
              :value="value"
              color="primary"
              v-if="loading">
              {{ value }}
            </v-progress-circular> 
            </div>-->
            <v-progress-linear background-color="blue-grey"
      color="lime" :indeterminate="true" v-if="loading"></v-progress-linear>
          </v-flex>
        </v-layout>
        <v-layout row wrap>
            <v-flex xs12 sm8 offset-sm2 v-if="!loading">
                <v-card>
                    <v-img
                        :src="meetup.imageUrl"
                        height="300px"></v-img>
                    <v-card-title>
                        <h3 class="primary--text"><strong>{{ meetup.title }}</strong></h3>
                        <template v-if="userIsCreator">
                          <v-spacer></v-spacer>
                          <app-edit-meetup-details-dialog :meetup="meetup"></app-edit-meetup-details-dialog>
                        </template>
                    </v-card-title>
                    <v-card-text>
                        <div>
                          <app-edit-meetup-date-dialog
                            :meetup="meetup"
                            v-if="userIsCreator"></app-edit-meetup-date-dialog>
                        </div>
                        <div class="info--text">{{ meetup.date | date }} | {{ meetup.location }}</div>
                        <div>{{ meetup.description }}</div>
                    </v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn round outline class="primary">Register</v-btn>
                    </v-card-actions>
                </v-card>
            </v-flex>
        </v-layout>
    </v-container>
</template>
<script>
export default {
  data () {
    return {
      interval: {},
      value: 0
    }
  },
  beforeDestroy () {
    clearInterval(this.interval)
  },
  mounted () {
    this.interval = setInterval(() => {
      if (this.value === 10) {
        return (this.value = 0)
      }
      this.value += 1
    }, 1000)
  },
  props: ['id'],
  computed: {
    meetup () {
      return this.$store.getters.loadedMeetup(this.id)
    },
    loading () {
      return this.$store.getters.loading
    },
    userIsAuthenticated () {
      return this.$store.getters.user !== null && this.$store.getters.user !== undefined
    },
    userIsCreator () {
      if (!this.userIsAuthenticated) {
        return false
      }
      return this.$store.getters.user.id === this.meetup.creatorId
    }
  }
}
</script>
<style scopedSlots>
.v-progress-circular{
    margin: 1rem
  }
</style>

这是我得到的全部错误 这是我的错误图片链接:https://imgur.com/a/nnDbhpA

  

这是我的EditMeetupTimeDialog.vue

<template>
  <v-flex xs12 sm6 md4>
      <v-dialog
        v-model="editDialog"
        persistent
        lazy
        full-width
        width="290px"
      >
        <v-btn slot="activator" flat outline small color="primary">Edit time</v-btn>
        <v-time-picker v-model="editableTime" format="24hr">
          <v-spacer></v-spacer>
          <v-btn flat color="primary" @click="editDialog = false">Cancel</v-btn>
          <v-btn flat color="primary" @click.native="onSaveChanges">Save</v-btn>
        </v-time-picker>
      </v-dialog>
    </v-flex>
</template>
<script>
  export default {
    props: ['meetup'],
    data () {
      return {
        editDialog: false,
        editableTime: null
      }
    },
    methods: {
      onSaveChanges () {
        const newDate = new Date(this.meetup.date)
        const hours = this.editableTime.match(/^(\d+)/)[1]
        const minutes = this.editableTime.match(/:(\d+)/)[1]
        newDate.setHours(hours)
        newDate.setMinutes(minutes)
        this.$store.dispatch('updateMeetupData', {
          id: this.meetup.id,
          date: newDate.getTime()
        })
      }
    },
    created () {
      this.editableTime = new Date(this.meetup.date).getTime()
    }
  }
</script>

并且我仍然使用getTime()和toISOString()出现错误

希望这个问题有意义。

注意:我正在使用最新版本的软件来处理我的练习项目

1 个答案:

答案 0 :(得分:2)

在Vuetify document中,传递给v-date-picker的值必须是数组或字符串。您可以转换:

 methods: {
       onSaveChanges () {
         const newDate = new Date(this.meetup.date)
         const newDay = new Date(this.editableDate).getUTCDate()
         const newMonth = new Date(this.editableDate).getUTCMonth()
         const newYear = new Date(this.editableDate).getUTCFullYear()
         newDate.setUTCDate(newDay)
         newDate.setUTCMonth(newMonth)
         newDate.setUTCFullYear(newYear)
         this.$store.dispatch('updateMeetupData', {
           id: this.meetup.id,
           date: newDate.toISOString().substr(0, 10)
         })
       }
    },
    created () {
      this.editableDate = new Date(this.meetup.date).toISOString().substr(0, 10)
    }