iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 26
0
Modern Web

菜菜菜的 Vue 30天系列 第 26

Vuex(安裝、引入、state 及 getters)

  • 分享至 

  • twitterImage
  •  

菜菜菜的 Vue 30天 - Day26

好的今天要介紹一下 Vuex 該怎麼安裝並引入

install

首先要使用 Vuex 當然要先安裝啦~

npm install vuex --save

安裝完成後也必須要引入才能夠做使用

引入

一般我們會在 src 路徑下創建一個 store 的資料夾,裡面再創建一個 index.js,將 Vuex 引入:

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {},
  actions: {},
  mutations: {},
  getters: {}
})
export default store;

接下來還要再 main.js 內將 Vuex 引入 Vue 內:

import store from './store/index'

new Vue({
    el: '#app',
    router,
    store,
    components: {
        App
    },
    template: '<App/>'
})

這樣我們就能夠透過 this.$store 來使用 Vuex 的方法囉~

state

我們前面有提到 Vuex 是讓我們能夠更好的管理我們的資料,想當然也會有一個地方來存放資料。

state 就是 Vuex 內用來存放資料的地方,就像是 Vue 實例內的 data 一樣。

存放資料的方式如下:

const store = new Vuex.Store({
  state: {
      message: 'Hi I am Andy~'
  }
})

我們就能透過以下方式來取得 state 的資料:

thie.$store.state.message

要特別注意的一點,若要使用 state 必須事先定義好,不要事後再去賦值,例如:

this.message = 'Yes!! I am Andy!!'

getters

Vuex 裡的 getters 其實就跟 Vue 的 computed 很像。

如果我們使用 state 需要計算或篩選...等就能夠使用 getters,該如何使用呢?

下面就來介紹如何使用:

const store = new Vuex.Store({
  state: {
      firstName: 'Andy',
      lastName: 'Tsai'
  },
  getters: {
    name(state) {
      return  `${state.firstName} ${state.lastName}` 
    }
  }
})

這樣子我們就設置好 getters 了,接下來就是在 Vue 裡面將值取出來,我們會在 computed 裡面作取值的動作,如下:

computed: {
    name(){
        return this.$store.getters.name;
    }
}

這章的介紹就到這,下一章繼續介紹 Vuex 的其他部分~


上一篇
Vuex
下一篇
Vuex(mutations)
系列文
菜菜菜的 Vue 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言