vuex的使用

文件目录
在这里插入图片描述

index.js


import Vue from 'vue'
import Vuex from 'vuex'
import router, { resetRouter } from '@/router'
// import resetrouter from '@/router/matcher'

import { getClick1, getClick2 } from '../api/request.js'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    count: 0,
    about: '关于我们的信息',
    age: 18,
    routers: []
  },
  mutations: {
    increment(state, data) {
      state.count += data
    },
    setAboutInfo(state, data) {
      state.about = data
    },
    setRouters(state, data) {
      // resetrouter(router)
      resetRouter(router)
      state.routers = data[0].children
      state.routers.map((item, index) => {
        if (item.meta.authority) {
          item.component = () => import('@/views/' + item.name + '.vue') // 必须异步引入 才能转为真正的组件
          router.addRoute(item)// 添加一条新的路由规则记录作为现有路由的子路由。如果该路由规则有 name,并且已经存在一个与之相同的名字,则会覆盖它
        }
      })
      console.log(router, 'router')
    }
  },
  // getters —用于对数据进行加工
  // getters中的方法可以拿到state中的数据并进行加工,
  // getters中的数据也可以在vue Devtools中看到。如果数据处理复杂或者会多次复用可以考虑使用getters。

  getters: {
    multiplicationAge(state) {
      return state.age * state.age
    },
    ageDivision(state, getters) {
      return getters.multiplicationAge / 2
    },
    // 如果要传参,可以return一个函数
    moreAgestu(state, getters) {
      return function(age) {
        return `state中的age和传入的age:${state.age}|${age},相加后${state.age + age},ageDivision的值为${getters.ageDivision}`
      }
    }
  },

  actions: {
    changeAboutInfo({ commit, state }, data) {
      console.log('调用了一次actions ', state.about)
      setTimeout(() => {
        commit('setAboutInfo', data)
        console.log('2s后的 about: ', state.about)
      }, 2000)
    },
    getRouterList({ commit, state }, data) {
      getClick1(data).then(res => {
        commit('setRouters', res.data)
        console.log(res, 'getClick1')
      })
    },

    getRouterList2({ commit, state }, data) {
      getClick2(data).then(res => {
        commit('setRouters', res.data)
        console.log(res, 'getClick2')
      })
    }
  }
})

页面App.vue

<template>
  <div id="app">


    <div >

      <div id="nav">
        导航
        <ul>
          <li><router-link to="/">Home</router-link></li>
          <li
            v-for="item in myrouters"

            :key="item.meta.id"
            style="padding: 5px 0; background: yellowgreen"
          >
            <div v-if="item.meta.authority">
              <router-link :to="{ path: item.path }">{{ item.name }}</router-link>

            </div>
          </li>
        <!-- <li><router-link to="/my">My</router-link></li>
        <li><router-link to="/userInfo">UserInfo</router-link></li> -->
        </ul>
      </div>
      <div style="border: solid 2px red">
        router-view:
        <router-view />
      </div>

      <hr>
      <button @click="click1">click 1</button>
      <button @click="click2">click 2</button>
      <hr>
      <h4>Vuex 使用</h4>
      <button @click="clickCountAdd">count ++</button>
      <div style="border: solid 2px #000">
        state数据的第一种使用方法: count:{{ $store.state.count }}
      </div>
      <hr>
      <div style="border: solid 2px #000">
        <!-- state数据的第二种使用方法: count:{{ mycounts }} -->
        <hr>
        <!-- state数据的第三种使用方法: count:{{ count }} -->
        <hr>
        state数据的第四种使用方法: count:{{ countFun }}
      </div>
      <hr>
      <div style="background: pink; padding: 25px">
        通过Actions的来提交
        <ul>
          <li>-Action 提交的是 mutation,而不是直接变更状态。</li>
          <li>-Action 可以包含任意异步操作。</li>
        </ul>
        about:{{ $store.state.about }}
        <button @click="clickAction">发送action 2s 后修改</button>
      </div>

      <div style="background: pink; padding: 25px; margin-top: 50px">
        getters的使用:

        <h3>普通写法{{ multiplicationAgeGetters }}</h3>
        <h3>乘法:{{ multiplicationAge }}</h3>
        <h3>对数据除2:{{ ageDivision }}</h3>
        <h3>乘法 as 别名:{{ asMultiplicationAge }}</h3>

        <hr>

        <h3>如果要传值:{{ moreAgestu(999) }}</h3>
      </div>
      <hr>

    </div>

  </div>
</template>
<script>
import { getClick1, getClick2 } from '../api/request.js'

import { mapMutations, mapState, mapActions, mapGetters } from 'vuex' // 第二种提交 mutations 的方式
export default {
  data() {
    return {

    }
  },
  mounted() {

  },
  // state数据的第二种使用方法
  // computed: mapState({
  //   mycounts: state => state.count
  // }),
  // state数据的第三种使用方法
  // computed: {
  //   ...mapState(['count']),
  // },
  // state数据的第四种使用方法
  computed: {
    countFun() {
      return this.$store.state.count
    },
    myrouters() {
      return this.$store.state.routers
    },
    multiplicationAgeGetters() {
      return this.$store.getters.multiplicationAge
    },
    // 使用对象展开运算符将getters混入computed对象中
    ...mapGetters([
      'multiplicationAge',
      'ageDivision',
      'moreAgestu'
    ]),
    ...mapGetters({
      asMultiplicationAge: 'multiplicationAge'
    })

  },

  methods: {
    // -----------------------------------------------------------
    ...mapMutations([
      // 'increment' // 将 `this.increment()` 映射为 `this.$store.commit('increment', 2)`
    ]),
    ...mapMutations({
      sendIncrement: 'increment' // 给他取个别名
    }),
    clickCountAdd() {
      // this.$store.commit('increment', 2)  //第一种提交 mutations 的方式

      // this.increment(3)//第二种提交 mutations 的方式
      this.sendIncrement(4) // 别名
    },
    // -----------------------------------------------------------

    // ...mapActions(['changeAboutInfo']),// 第二种 actions 分发
    ...mapActions({
      newNameChangeAboutInfo: 'changeAboutInfo', // 别名  第三种 actions 分发
      getRouter: 'getRouterList',
      getRouter2: 'getRouterList2'
    }),
    clickAction() {
      // 第一种 actions 分发
      // this.$store.dispatch('changeAboutInfo', 'about 新的修改')

      // 第二种 actions 分发
      // this.changeAboutInfo('about 新的修改 第二种 actions 分发')

      this.newNameChangeAboutInfo('三种 actions 分发')// 第三种 actions 分发
    },
    // -----------------------------------------------------------

    click1() {
      this.$router.replace({ path: '/home' })

      this.getRouter({ test: 'testaaa999' })

      // getClick1({ test: 'testaaa999' })
      //   .then(res => {
      //     console.log(res, 'getClick1')

      //   })
    },
    click2() {
      this.$router.replace({ path: '/home' })

      this.getRouter2({ test: 'testbbbb77777' })

      // getClick2({ test: 'testbbbb77777' })
      //   .then(res => {
      //     console.log(res, 'getClick2222')
      //   })
    }
  }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

console.log(store.state.count) // 1
store.commit('increment')


actions异步函数的用法

this.store.dispatch(“funcionName”)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值