1. vue 实时获取时间

now: new Date()
mounted() {
 setInterval(()=>{
 	this.now = new Date()
 }, 1000)
}

2. 获取服务器的时间,防止本机时间获取错误

  • 场景: 本机经常关机,时间获取不同步,但是服务器时间是同步的,需要获取服务器的时间显示
  • 解决办法:
    - 1. 在后端服务器的响应头部可以获取date,
    - 2. 使用简单状态管理store来获取本地时间与服务器的时间差
    - 3. 混入到需要使用的组件中
  • 代码
// store 
var store = {
  debug: true,
  state: {
    differTime: ''
  },
  changeTIme (newValue) {
    if (this.debug) console.log('setMessageAction triggered with', newValue)
    this.state.differTime = valueOf(new Date()) - valueOf(newValue) // 时间戳的差值
  }
}

// request.js
import store from 'store'
// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
  // 获取服务器时间
  	if(response.header.date) {
  		store.changeTime(response.header.date)
  	}
    return response
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

// minxin.js 使用公共状态store
import store from '../xx/store'
export default {
	data() {
		return {
			storeState: store.state // {differTime: ''}
			myState: {
				currentTime: ''
			}
		}
	},
	computed: {
		formatTime() {
			return this.$moment(this.currentTime).format('YYYY-MM-DD HH:mm:ss')
		},
		formatMonth() {
			return this.$moment(this.currentTime).format('YYYY-MM')
		},
		formatYear() {
			return this.$moment(this.currentTime).format('YYYY')
		}
	},
	mounted() {
		this.timer = setInterval(() => {
			this.currentTime = new Date( valueOf(new Date()) + this.storeState.differTime)
		},
		1000)
	}
}

// xxx.vue中使用

import myMixin from 'xxx'
export default {
	 mixins: ['myMixin'],
	 data() {return {}}
	}
	
// 则可以使用this.myState.formatTime ......

VUEX 总结

– 上面使用了简单状态管理,具体参考官网说明,只提供了全局变量,和操作变量的方法

  • 相当于使用了Vuex中的state, 和mutations功能, 没有getters, actions, modules(五大功能)

  1. 不能直接改变state里的数据。

  2. mutations:通过执行 this.$store, commit('mutation名称', payload)来触发 mutation 的调用, 间接更新 state

  3. actions 组件中: this.$store.dispatch(‘action 名称’, data1),actions中可以包含异步代码(例如:定时器, 请求后端接口), actions中调用mutations的函数,可以监听操作state的变化

  4. getters可以获取state中经过计算的属性, 类似vue中computed属性,具有缓存功能

  5. namespace 可以使用模块化

         // 分模块,不改方法名
       ...mapActions('模块名', ['actions方法名'])    ||     -------通常放在methods
       ...mapState(模块名', ['state名称'])        ---- 通常放在computed中
       ...mapGetters ('模块名', [ 'getters名称'  ])   ---- 通常放在computed中
       ...mapMutations ('模块名', [ 'mutations名称'  ])   -------通常放在methods
    
    或者使用  ...mapActions(['模块名/ 方法名'])   
    
    调用函数
    this.$store.dispatch("user/test", "value")  // 第二个参数为传参
    
import {createStore} from 'vuex'
import collapse from "./modules/collapse";
import authState from './modules/auth';
 
export default createStore({
    modules: {
        collapse,
        authState 
    },
})

//auth.js
const authState = {
    namespaced: true, // 开启命名空间
    state: {
        count: 0,
    },
    mutations: {
        setCount(state, data) {
            state.count= data
        },
    },
    actions: {},
    getters: {
        count: state => state.count,
    }
}
export default authState 

—完美!!!

Logo

前往低代码交流专区

更多推荐