關於vuex的一些小事

第一次寫技術文章仍是蠻激動的,先從哪裏下手好呢?先說說vuex是什麼吧,官方文檔是這麼解釋的:vue

Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。Vuex 也集成到 Vue 的官方調試工具 devtools extension,提供了諸如零配置的 time-travel 調試、狀態快照導入導出等高級調試功能。git

我理解過來就是:github

狀態的儲存站以及全局數據(可能會有些誤差)

怎麼在vue項目中使用vuex呢
首先安裝vuex

npm istall vuex

而後在main.js裏引入vuexnpm

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

每個 Vuex 應用的核心就是 store(倉庫)。"store" 基本上就是一個容器,它包含着你的應用中大部分的狀態(即 state)segmentfault

在例子中,直接建立了一個store.js文件來保存倉庫的信息:app

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 做爲第一個參數flex

由於是收藏夾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

相關文章
相關標籤/搜索