关于vuex的一些小事

第一次写技术文章还是蛮激动的,先从哪里下手好呢?先说说vuex是什么吧,官方文档是这么解释的:

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

我理解过来就是:

状态的储存站以及全局数据(可能会有些偏差)

怎么在vue项目中使用vuex呢
首先安装

npm istall vuex 

然后在main.js里引入vuex


    //main.js
    import Vuex from 'vuex'
    Vue.use(Vuex)

每一个 Vuex 应用的核心就是 store(仓库)。"store" 基本上就是一个容器,它包含着你的应用中大部分的状态(即 state)

在例子中,直接创建了一个store.js文件来保存仓库的信息:


    const store = {
        state: {
            starList: [{
                title: "掘金",
                href: "https://gold.xitu.io/"
            },{
                title: "GitHub",
                href: "https://github.com/"
            },{
                title: "SegmentFault",
                href: "https://segmentfault.com/"
            }]
        }
    }
    
    module.exports = store

在main.js中引入它,并初始化Vuex.Store:


    //main.js
    import stores from './store'
    const store = new Vuex.Store(stores)
    
    new Vue({
      el: '#app',
      store,
      template: '<App/>',
      components: { App }
    })

state作为store的唯一数据源而存在,在组件里可以使用this.$store.state来获取,但是这个数据是只读的,无法直接通过给this.$store.state赋值来达到赋值的效果,这时就轮到mutation出场了.

mutation是唯一能更改store中的状态(state)的方法,这个相当于事件,每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

因为是收藏夹demo,所以应该有一个添加的功能,给store加上一个可以添加item的方法:


    //store.js
    mutations: {
        addStarList(state,obj) {
            state.starList.push(obj)
        }
    }

好了,现在store已经基本完成,接下来就是组件里如何使用这个store了

在子组件中:


    <template>
        <div class="list">
          <input type="text" name="title" v-model:value="name" placeholder="名字">
          <input type="text" name="href" v-model:value="href" placeholder="href">
          <button type="button" @click="add(name,href)">添加</button>
          <h2>我的收藏</h2>
          <ul class="star-list">
            <li class="item" v-for="item of starList">
              <a :href="item.href">{{item.title}}</a>
            </li>
          </ul>
        </div>
    </template>
    
    <script>
    import {mapState,mapMutations} from 'vuex'
    export default {
      name: 'hello',
      data () {
        return {
          name: '',
          href: ''
        }
      },
      computed: {
        ...mapState([
        'starList'
      ])
      },
      methods: {
        ...mapMutations([
          'addStarList'
        ]),
        add(name,href) {
          console.log(name,href);
          this.$store.commit('addStarList',{
            title: name,
            href: href
          })
        }
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
      ul,li {
        list-style: none;
        margin: 0;
        padding: 0;
      }
    
      .star-list {
        display: flex;
        /*flex-direction: row;
        flex-wrap: wrap;*/
        flex-flow: row wrap;
        justify-content: space-between;
        align-items: center;
      }
    
      .item {
        text-align: center;
        width: 30%;
        margin-bottom: 20px; 
      }
    
      .item a {
        text-align: center;
        text-decoration: none;
        color: #367;
        font-size: 18px;
      } 
    </style>

用v-module绑定了表单的值,这样才能将输入的值更新。
在这里解释一下mapState以及mapMutation

mapState 当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用
mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

mapState让我们可以不用再写this.$store.state.状态名 来获取状态,而是可以直接使用状态名获取

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations
辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

mapMutation是一个辅助函数,让我们不需要再写繁琐的this.$store.commit('functionName')来触发事件,而是可以直接的使用functionName()

主要代码:Demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值