1. 程式人生 > >vuex狀態管理器

vuex狀態管理器

安裝

cnpm i vuex –save

使用

建立檔案store.js引入必須檔案

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

增加常量物件

const state={
    count:1
}

用export default 封裝程式碼,讓外部可以引用。

export default new Vuex.Store({
    state
})

在vue模板中使用

<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
>

修改vuex中的物件

在store.js檔案中加入兩個改變state的方法

const mutations={
    add(state){
        state.count++;
    },
    reduce(state){
        state.count--;
    }
}

元件模板中使用

<div>
    <button @click="$store.commit('add')">+</button>
    <button @click="$store.commit('reduce')">-</button
>
</div>