Vuex使用 1 加簡單案例

Vuex使用 1

1、安裝 vuex。在控制命令行中輸入下邊的命令就可以了。

npm n install vuex --save

2、新建store.js文件(可以新建一個文件夾放),文件中引入我們使用的vue和vuex。

import Vue from 'vue';
import Vuex from 'vuex';
//使用vuex,引入之後要Vue.use引用。
Vue.use(Vuex);

現在vuex就算引用成功!!!!!!
*

案例:

(大牛 :技術胖的案例)
先聲明一個state的count狀態,在頁面中使用顯示這個count,然後可以利用按鈕進行加減
在這裏插入圖片描述

用的是vuex來進行製作,並實現數據的共享。

1.在store.js文件裏增加一個常量對象。store.js文件就是在引入vuex時的文件。

const state={
    count:1
}

2.還是在store.js 用export default 封裝代碼,讓外部可以引用。

export default new Vuex.Store({
    state
})

3.在新建一個vue的模板,位置在components文件夾下,新建vue頁面。在模板中我們引入新建的store.js文件,並在模板中用{{$store.state.count}}輸出count 的值。

<template>
    <div>
        <h2>{{msg}}</h2>
        <hr/>
        <h3>{{$store.state.count}}</h3>
    </div>
</template>
<script>
    import store from '@/vuex/store'
    export default{
        data(){
            return{
                msg:'Hello Vuex',
            }
        },
        store   <<-------這裏一定要加上
    }
</script>

4.在store.js文件中加入兩個改變state的方法。

const mutations={
    add(state){
        state.count++;
    },
    reduce(state){
        state.count--;
    }
}
//並在export default 中添加方法
export default new Vuex.Store({
    state,
    mutations  <<------ //這裏
})

這裏的mutations是固定的寫法,意思是改變的,要改變state的數值的方法,必須寫在mutations裏就可以了。
5.在vue頁面模板中加入兩個按鈕,並調用mutations中的方法。

<div>
    <button @click="$store.commit('add')">+</button>
    <button @click="$store.commit('reduce')">-</button>
</div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章