Vue.js 2.x筆記:狀態管理Vuex(7)

1. Vuex簡介與安裝

1.1 Vuex簡介

  Vuex是爲vue.js應用程序開發的狀態管理模式,解決的問題:html

    ◊ 組件之間的傳參,多層嵌套組件之間的傳參以及各組件之間耦合度太高問題vue

    ◊ 不一樣狀態中的行爲須要多份複製的問題node

  Vuex採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。vuex

  核心思想:抽取組件的共享狀態,以一個全局單例的模式進行管理。vue-cli

  核心:store(倉庫)npm

  核心組成:app

    ◊ state:存放項目中須要多組件共享的狀態變量異步

    ◊ getters:讀取器,存放更改state裏狀態的方法ide

    ◊ mutations:修改器,從state中派生出狀態,如:將state中的某個狀態進行過濾而後獲取新的狀態。模塊化

    ◊ actions:動做,mutation的增強版,能夠經過commit mutations中的方法來改變狀態,最重要的是能夠進行異步操做。

    ◊ modules:模塊化,將狀態和管理規則模塊化封裝。

    

  Vuex文檔:https://vuex.vuejs.org/zh/

1.2 Vuex安裝

  npm安裝:

npm install vuex -S

  基礎示例:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>libing.vue</title>

    <script src="node_modules/vue/dist/vue.min.js"></script>
    <script src="node_modules/vuex/dist/vuex.min.js"></script>
</head>

<body>
    <div id="app">
        Copyright &copy; {{ author }} - 2018 All rights reserved
    </div>

    <script>
        Vue.use(Vuex);

        const store = new Vuex.Store({
            // 定義狀態
            state: {
                //key: value
                author: 'Libing'
            }
        });

        new Vue({
            el: "#app",
            store: store,
            computed: {
                author: function () {
                    return this.$store.state.author
                }
            }
        });
    </script>
</body>

</html>

  vue-cli示例:

  

  /store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    // 定義狀態
    state: {
        //key: value
        author: 'libing'
    }
})

  HelloWorld.vue

<template>
    <div>Copyright &copy; {{ author }} - 2018 All rights reserved</div>
</template>

<script>
export default {
    name: "HelloWorld",
    computed: {
        author: function() {
            return this.$store.state.author;
        }
    }
};
</script>
<template>
    <div id="app">
        <HelloWorld/>
    </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
    name: "App",
    components: {
        HelloWorld
    }
};
</script>
App.vue

  main.js

import Vue from 'vue'
import App from './App'

import store from './store/index'

Vue.config.productionTip = false

new Vue({
    el: '#app',
    store,
    components: {
        App
    },
    template: '<App/>'
})
相關文章
相關標籤/搜索