08——去哪网(vuex实现数据共享)

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的

这个状态自管理应用包含以下几个部分:

state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化在这里插入图片描述在这里插入图片描述

安装

npm install vuex --save

引用:
(新建store文件夹,创建index.js文件,写下如下代码)

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

Vue.use(Vuex)

export default new Vuex.Store({
  state:{
    city:'皇马'
  }
})

使用

import store from './store/index'


<div class="header-right">
        {{this.$store.state.city}}
</div>

例子讲解:
这是一个组件里面,想通过dispatch传参city到vuex中
(this.$store.commit(‘changeCity’,city);)通过commit也可以

 methods:{
    handleHotCityClick (city) {
      this.$store.dispatch('changeCity',city)
      alert(city)
    }
  },

city值先通过actions里的changeCity方法获取city参数,
再提交到mutations的changeCity 方法里,在changeCity 方法里把state.city 的值设为传过来的city值

export default new Vuex.Store({
  state:{
    city:'皇马'
  },
  actions: {
    changeCity (ctx,city) {//ctx上下文参数
      ctx.commit('changeCity',city)
    }
  },
  mutations:{
    changeCity (state,city) {
      state.city = city
    }
  }
})

此时会存在几个问题:

  1. 选好city后,再刷新,一切又会变成默认值了
  2. 故而使用localStorage来进行本地存储
  3. 但有的浏览器不行,所以,使用localStorage一定要用trycatch
  4. 此时index.js文件就会变得很杂了,我们把它模块化,在store文件夹下,再建几个js文件来存放state和mutations,再在index中引入
 {{this.$store.state.city}}  //很冗余

可改成{{this.city}}
但要加上

import { mapState } from 'vuex'

 computed:{
    ...mapState(['city'])  //把city共用数据映射到city的计算属性中,...是展开运算符
    
  }

vuex里的getters属性与计算属性差不多,可避免数据冗余
vuex的module,把store分隔成module

使用keep-alive优化网页性能
app.vue

<template>
  <div id="app">
    <keep-alive>
      <router-view/>
    </keep-alive>
  </div>
</template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值