vue中高级应用

vuex中高级应用

serverInLocal.js 文件

export default store => {
if (localStorage.state) store.replaceState(JSON.parse(localStorage.state))
store.subscribe((mutation, state) => {
	localStorage.state = JSON.stringify(state) // 存储一个store数据,当页面刷新后,重新将此对象赋值给当前store,能保持store是刷新前的状态
} )

store 中 index.js 文件

import user from './modules/user'
import serverInLocal from './serverInLocal.js'
export default new Vuex.Store({
	strict: process.env.NODE_ENV === 'development' // 严格模式下,如果直接用赋值的形式修改store中的值,虽然可以修改成功,但是控制台会报错
	state,
	getter,
	mutations,
	actions,
	modules: {
		user
	},
	pulgins: [serverInLocal ]
})

让vuex中的值实现双向数据绑定

<template>
	<input v-model="stateValue"/>
</template>
<script>
	import (mapMutations, mapActions) from 'vuex'
	...
	computed: {
		...mapMutations(['SET_STATE_VALUE']),
		stateValue: {
			get: function() {
				return this.$store.state.stateValue
			}
			set: function(value) {
				this.SET_STATE_VALUE(value)
			}
		}
	}
</script>
const state = {
	stateValue : ''
}
const mutations = {
	SET_STATE_VALUE: function(state, value) {
		this.stateValue = value
	}
}

实现class动态绑定

<template>
	<Icon :class="triggerClasses" @click.native="handleCollapsed" type="md-menu" :size="32"/>
	在icon组件中没有click事件,这里用.native修饰符将事件绑定到这个组件的最外层div上
</template>
computed: {
    triggerClasses () {
      return [
        'trigger-icon',
        this.collapsed ? 'rotate' : '' // 注意这里的代码,在style中怎么写
      ]
    },
    ...mapState({
      tabList: state => state.tabNav.tabList,
      routers: state => state.router.routers.filter(item => {
        return item.path !== '*' && item.name !== 'login'
      })
    })
  }

<style>
	.trigger-icon{
      cursor: pointer;
      transition: transform .3s ease;
      &.rotate{ // 注意这里和computed中对应
        transform: rotateZ(-90deg);
        transition: transform .3s ease;
      }
    }
</style>

你可能感兴趣的:(js)