part7 vuex实现数据共享

vuex 是数据框架(一个插件)(单项数据的改变流程,组件改数据必须先调Action用dispatch方法)

 大型项目vue只能承担视图层的主要内容 

大量数据传递的时候,往往需要一个数据框架辅助

例子:多个组件之间的传值很困难的时候,如果我们能吧公用的数据放在一个公共的空间

存储,然后某一个组件改变了数据,其他组件能够感知

start

1.因为vuex做的文件还是比较复杂的,所以我们先创建一个单独的文件夹

/src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default  new Vuex.Store({})

2.然后在main.js中引入,便可在所有组件中使用

import store from ''./store"

new Vue({
    store,    //传进根实例
})

3.组件中使用

{{this.$store.state.city}}

4.组件中改变数据

首先组件中调用VUEX中的Actions 用 dispatch方法

然后actions调用Mutations用commit方法

this.$store.dispatch('changeCity', city)  //city为数据 ,派发一个名字叫changCity这样一个Action
//Action需要写在 Store中
export defalut new Store({
   state: {}
   action: {
   chageCity (ctx, city) {} 
   ctx.commit('chageCity', city)   //ctx为执行上下文
}  
   mutations: {
    changeCity('state','city') {
      state.city = city
}
} 
})

当数据比较简答的时候 可以直接调用mutations

this.$store.commit('changeCity', city)

页面跳转方法

1.a标签

<router-link to="/"> </router-link>

 

2.js window.location.href

this.$router.push('/')

 


本地存储(页面刷新后,内容不变)

如果用户关闭了本地存储功能活着隐身模式 就不能用localstorage

 所以对于使用localstorage 要做错误捕获,不用处理

我做错

try {
  var lastCity = localStorage.city || '上海'
} catch (e) { }  //如果隐身模式,loacalstarage.city 就会报错 不会传旨‘sh’

修正后

var lastCity = '上海'
try {
  if (localStorage.city) {
    lastCity = localStorage.city
  }
} catch (e) { }

 

 

vuex 高级用法

1.当index文件庞大之后,可以拆分 state mutations 文件组件化

1.创建state.js 文件  
然后 export default {}
然后 index.js  import 一下

2.模板中引用的state数据太长 我们可以用高级api

import { mapState } from 'vuex'
computed: {
...mapState(['city'])
}

//然后模板中直接 this.city就可以了

import { mapState } from 'vuex'
computed: {
...mapState({
currentCity: 'city'
})
}

//也可以

3相同的script标签中用的 调用matations也可以简化

import { mapState, mapMutations } from 'vuex'
computed: {
...mapState(['city'])
}
    

methods: {
    handleClick (city) {
        this.changeCity(city)
    }
     ...mapMutations(['changeCity']) //我们又一个mutations叫 changeCity,
我们把它映射到 changecity的方法里 那么我们要调用这个macations

4.getters

//index.js  film
export default new Vuex.Store({
   getters: {
   doubleCity(state) {
   return state.city + "" 
} 
}
})
//当我们需要根据state计算新的数据.避免数据冗余,类似computed
import { mapState,mapGetters } from 'vuex'
computed: {
...mapState(['city']),
...mapGetters('doubleCity') } //然后模板中直接 this.city就可以了 import { mapState } from 'vuex' computed: { ...mapState({ currentCity: 'city' }) } //也可以
 

5.非常复杂的业务场景,管理后台系统的时候,很多公用数据在vuex中储存

借助module复杂的motations Actions 拆分

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

 

posted @ 2020-02-15 15:02  容忍君  阅读(313)  评论(0)    收藏  举报