vueX

作者: 未来在奋斗 | 来源:发表于2019-12-01 21:17 被阅读0次

    vuex

    管理什么状态呢

    • token 登录状态
    • 用户名称,头像,地理位置
    • 收藏,购物车中的物品

    这些可以对他们进行保存和管理,而且还是响应式的

    安装VueX

    npm install vuex --save
    

    创建 store文件夹创建index.js文件

    import Vue from 'vue'
    import Vuex  from 'vuex'
    
    // 托管
    Vue.use(Vuex);
    // 3 创建对象
    const store = new Vuex.Store({
        state:{
            //保存状态,数据
            cum:1000
        },
      mutations:{
          //方法 修改state的唯一操作就是提交mutation只能在这里修改只处理同步
          add(state){
                    state.cum++
                    },
              cdd(state){
                     state.cum--;
               }
          /  在使用页面监听事件
        methods:{
                  addition(){
                        this.$store.commit('add')
                  },
              cddition(){
                this.$store.commit('cdd')
                  }
         }
    /**
         * 移除购物车中的某个商品
         */
        delCar (state) {
          console.log('移除购物车中的某个商品')
        }
    },
        actions:{ //用来处理异步
                     /**
         * 异步添加商品到购物车
         */commit和state差不多
        addCarAsync ({ commit, state, getters }, id) {
          // console.log('异步添加商品到购物车')
          // 需要先将数据调用后端接口来存储到数据库中,
          // 然后把本地的仓库也给更新。
          // console.log(context.getters)
          console.log('异步添加数据 begin')
          setTimeout(() => {
            console.log('异步添加数据 end')
    
            // 在通过 context.commit() 来调用 mutation
            commit('addCar', id)
          }, 1000)
        },
    
        /**
         * 异步移除购物车中的某个商品
         */
        delCarAsync (context, payload) {
          console.log('异步移除购物车中的某个商品', payload)
        }
    },
        getters:{ //store的计算属性},
        modules:{//对仓库分割成模块 }
    })
    
    // 4 导出
    export default store
    

    在main.js中写引入store

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import store from './store'
    Vue.config.productionTip = false
    
    new Vue({
      el:'#app',
      router:router,
      store:store,
      render: h => h(App),
    })
    
    

    调用修改数据

    <template>
      <div>
        <h1>商品页面 - {{ fullName }}</h1>
    
        <p>商品的数量:{{ goodNum }}</p>
        <ul>
          <li v-for="item in goods" :key="item.id">
            {{ item.id }} - {{ item.name }} - {{ item.price }} -
            <button @click="addCarAsync(item.id)">+</button>
            <button @click="delCarAsync(item.id)">-</button>
          </li>
        </ul>
      </div>
    </template>
    
    <script>
    import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
    
    export default {
      data () {
        return {
          firstName: '张',
          lastName: '三'
        }
      },
    
      computed: {
        ...mapState(['goods']),
        fullName () {
          return this.firstName + '' + this.lastName
        },
        // goodNum () {
        //   return this.$store.getters.goodNum
        // }
        ...mapGetters(['goodNum'])
      },
    
      methods: {
        ...mapMutations(['addCar']),
        ...mapActions(['addCarAsync']),
        // fn1 (id) {
        //   setTimeout(() => {
        //     // 调用 mutation
        //     // this.$store.commit('addCar', id)
        //     this.addCar(id)
        //   }, 1000)
        // }
        // addCar (id) {
        //   this.$store.commit('addCar', id)
        // }
        delCarAsync (id) {
          // this.$store.dispatch('delCarAsync', id)
          this.$store.dispatch({//提交异步的方法
            type: 'delCarAsync',
            id: id
          })
        }
      },
    
      created () {
        console.log(this.$store)
      }
    }
    </script>
    
    <style>
    
    </style>
    
    

    使用store保存的数据直接调用

    <template>
      <div id="app">
       <!-- <router-link to = '/home' tag="button" replace active-class="laozhang">首页</router-link>
    
        <router-link to = "/about" tag="button" replace active-class="laozhang">关于</router-link> -->
       <button @click="fn1">首页{{$store.state.cum}}</button>
        <button @click="fn2">关于页</button>
        <router-link :to = "'/user/'+userId" tag="button" replace active-class="laozhang">用户</router-link> 
          <!-- <router-link to = "/profile" tag="button" replace active-class="laozhang">用户</router-link>  -->
         <!-- <router-link :to = "{path:'/profile',query:{name:'laowang',age:18}}" tag="button" replace active-class="laozhang">用户</router-link>  -->
         <!-- <router-link @click="fn3"  tag="button" >档案</router-link>  -->
            <button @click="fn3" >档案</button>
     <keep-alive exclude="profile,user">
       <router-view>    </router-view>
       </keep-alive>
    </div>
    </template>
    
    
    

    mapState(); state辅助函数 获取数据
    mapGetters();getters 辅助函数
    mapMutations(); mutations辅助函数 提交方法数据修改数据
    mapActions(); actions辅助函数

    vuex

    vue 官方提供的状态管理器

    使用步骤

    1. 下载
    npm install --save vuex
    
    1. 在 src 下创建一个 store/index.js 文件,这个文件就是 仓库的配置文件

    2. 需要在 main.js 中引入第2步中暴露出来的仓库的实例对象。并配置在 new Vue() 的地方,通过 store 选项配置。

    $store

    使用了 vuex 之后,自动绑定到vue实例上的数据,这个数据就是当前vuex仓库的实例对象

    1. 如何将仓库中的state数据拿到组件中使用

    1. this.$store.state.xxxx 的方式 (不推荐)
    2. 通过computed去取出仓库中的数据 (推荐)
      ?为什么使用仓库中state的数据需要在computed中取出?
      !state数据不允许直接修改,用在computed上更好,如果修改,会报错!
    3. 使用 mapState() 这个辅助函数的方式 (更推荐)

    2. 如何将仓库中的getter数据拿到组件使用

    1. this.$store.getters.xxx 的方式 (不推荐)
    2. 通过computed去取出仓库中getter的数据(推荐)
    3. 使用 mapGetters() 辅助函数 (更推荐)

    3. 如何修改仓库中的 state 数据呢

    1. this.$store.commit('mutation的名字', payload)
    2. 通过 mapMutations() 辅助函数 (更推荐)

    相关文章

      网友评论

          本文标题:vueX

          本文链接:https://www.haomeiwen.com/subject/qwbfgctx.html