vuex

80 阅读2分钟

1. Vuex

  1. 使用流程 * 先下载包vuex * 在src文件夹中创建一个store文件夹,创建一个index.js文件 * 在顶部位置结构vuex导入createStore * const store = createStore({}) * 末尾位置导出store * 在main.js中导入import store from '@/store/index' * 在main.js中给app挂在上app.use(store)

  2. state * 类似于vue中的data js state(){ return{ count:1 } } * 在html结构中调用{{$store.state.count}}

  3. mutations * 类似于vue中的methods但是不能书写异步代码 js mutations:{ add(state){ state.count++ }, addNum(state,value){ state.count+=value } } * 想要在组件中触发可以用@click='this.store.commit(add)@click=this.store.commit('add')' * @click='this.store.commit('addNum',100)'

  4. actions * 和mutations类似但是可以书写异步代码 js actions:{ yibu(context){ setTimeout(()=>{ context.commit('add') <!-- 这样可以延时一秒调用add函数 --> },1000) } } * 在html结构中调用@click='this.$store.dispatch('yibu')' * 通过 mapActions 将方法结构到 methods, 后续直接使用

    ...mapActions(["asyncAddCount"])
    
  5. getter * 和vue中的计算属性类似 js getter(context){ context.commit(){ console.log(123) } } * $store.getters.计算属性名 * 通过 mapGetters 将方法结构到 computed, 后续直接使用

    ...mapGetters(['getCount'])
    
  6. modules * vuex是将公共的数据放到一个类似于仓库的东西中,就类似于定义一个全局变量,在这个项目中所有的地方都可以用,这个modules类似于给这个仓库添加一个限制,modules可以书写state,mutations,actions,getters,相当于里面书写在每一个自己的作用域内 js $store.state.创建好的文件名(stu).响应式数据

2. 可以数据持久化的包

  1. vuex-persistedstate

  2. plugins: ['一个函数()'] plugins是vuex中添加插件的地方,这个写法会将state中的所有数据做本地存储

  3. 下面这个写法可以只存储指定的数据

plugins: ['一个函数({reducer:(state)={return{count:state.count}}})']
plugins: [createPersistedState({
    reducer: (state) => {
      return {
        count: state.count,
        userInfo: state.userInfo
      }
    }
  })],

3. 拦截器

    // 拦截器应该添加在axios使用的地方其中axios可以换成你定义的发送请求的单词(事件)
    // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

  // 添加响应拦截器
  axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
    return response.data
    // 上边这个返回的是请求完成后res返回的数据
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

4. mapMutations

  1. 是一个vuex提供的辅助函数可以帮我们把需要的函数的结构到指定的组件位置内(通常放在methods中)
import mapMutations from 'vuex'
...mapMutations(['相结构的函数的函数名']),

可以代替

this.$store.commit('addNum',100)
<!-- 用的就是 -->
this.结构出来的文件名('要传入的参数')

5. children

  1. 子集路由children:[{},{}]

  2. el-menu有一个属性是router:true可以实现跳转对el-menu中的子集标签的index进行跳转