【vuex入門系列01】實戰操做加減法案例對vuex感知


官方文檔

https://vuex.vuejs.org/zh-cn/vue

如下操做所有放在了這個項目當中

https://github.com/itguide/vu...webpack

Vuex 是什麼?

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

狀態:驅動應用的數據源

想一想一下,angular裏面的service
controller -> service
在service 裏面請求api
在controller裏面調用service
service1
好比github

controller1 -> service1
controller2 -> service1

若是你把驅動應用的數據源如今寫在一個組件裏面,只針對這個組件來用。
若是寫在vuex裏面的state 裏面,任何組件均可以調用。web

什麼狀況下我應該使用 Vuex?

雖然 Vuex 能夠幫助咱們管理共享狀態,但也附帶了更多的概念和框架。這須要對短時間和長期效益進行權衡。

若是您不打算開發大型單頁應用,使用 Vuex 多是繁瑣冗餘的。確實是如此——若是您的應用夠簡單,您最好不要使用 Vuex。一個簡單的 global event bus 就足夠您所需了。可是,若是您須要構建是一箇中大型單頁應用,您極可能會考慮如何更好地在組件外部管理狀態,Vuex 將會成爲天然而然的選擇。引用 Redux 的做者 Dan Abramov 的話說就是:

Flux 架構就像眼鏡:您自會知道何時須要它。vue-router

使用方式

如下操做所有放在了這個項目當中

https://github.com/itguide/vu...vuex

vuex 安裝

安裝方式1:使用NPM

npm install vuex --save

安裝方式2:使用yarn

yarn add vuex

在vuexbase項目中使用

在一個模塊化的打包系統中,您必須顯式地經過 Vue.use() 來安裝 Vuex:chrome

初始化項目

vue init webpack vuexbasenpm

在項目文件中src裏面api

建立一個文件 stroe

在store 裏面新建一個index.js

index.js 文件內容以下

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

Vue.use(Vuex)

let store = new Vuex.Store({
    state: {
        num: 100
    }
})

export default store

在src/main.js 裏面引入 vuex

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store' //引入vuex

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,  // 須要在添加
    template: '<App/>',
    components: { App }
})

devtoos vue工具地址

https://chrome.google.com/web...

建立一個組件

Increment.vue

<template> 
    <div>
        <h2>加減法計算器</h2>
        <div>
            <input type="button" value="-" @click="minHandle"/>
                <span>{{num}}</span>
            <input type="button" value="+" @click="addHandle"/>
        </div>
    </div>
</template>
<script>
    export default {
        data(){
            return {
                // num:100
                num: this.$store.state.num,
            }
        },
        methods:{
            addHandle(){
                this.num += 5;
            },
            minHandle(){
                this.num -= 5;
            }
        }
    }
</script>

修改一些路由

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Increment from '@/components/Increment'

Vue.use(Router)

export default new Router({
    routes: [{
        path: '/',
        name: 'Hello',
        component: Increment
    }]
})

vuex的狀態在組件裏面怎麼調用?

$store 在main裏面引入了以後,記得在
在這個裏面加入
new Vue({
    el: '#app',
    router,
    store,  // 須要在添加
    template: '<App/>',
    components: { App }
})

在組件調用方式:
this.$store.state.num

此時就運行項目會發現以下
npm run dev

image_1bs7n2ht9qh71chi188t17v91nmu9.png-20.4kB

相關文章
相關標籤/搜索