Vuex的基本概念、專案搭建、入坑點
阿新 • • 發佈:2018-11-03
前言:Vuex是一個專門為Vue.js應用程式開發的狀態管理模式, 它採用集中式儲存管理所有元件的公共狀態, 並以相應的規則保證狀態以一種可預測的方式發生變化.
Vuex的四大核心
1.state 驅動應用的資料來源
2.mutations 基因突變 類如C# 屬性get set
3.actions 行為
4.getters 讀取器
上圖中綠色虛線包裹起來的部分就是Vuex的核心, state
中儲存的就是公共狀態, 改變state
的唯一方式就是通過mutations
進行更改. 可能你現在看這張圖有點不明白, 等經過本文的解釋和案例演示, 再回來看這張圖, 相信你會有更好的理解.
如何引入Vuex?
1.npm install vuex
2.裝好了之後,在全域性上去使用你的Vuex
3.建立Store物件,最好在src建立一個store這樣的資料夾然後建立index.js
4.在main.js中註冊使用
import Vuex from 'vuex' Vue.use( Vuex ); const store = new Vuex.Store({ //待新增 }) new Vue({ el: '#app', store, render: h => h(App) })
為了講解Vuex,我們做了一個專案,這個專案需要連線apicloud,非同步操作使用了axios以及樣式bootstrap,其中包括了登入註冊以及其中的父元件向子節點傳值等,我們給專案安裝相關的modules
npm install bootstrap
npm install axios
router.js
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'index', component:()=>import('../views/index.vue') }, { path:'/detail/:id', name:'detail', component:()=>import ('../views/detail.vue') }, { path:'/login', name:'login', component:()=>import ('../views/login.vue') }, { path:'/register', name:'register', component:()=>import ('../views/register.vue') } ] })
store.js
import Vue from 'vue' import Vuex from 'vuex' import API from '../utils/api.js' var api = new API('goods') var userApi = new API('userinfo'); Vue.use(Vuex); const state = { user: null, products: [] } const mutations = { //載入產品資料 INIT_PRODUCTS(state, data) { state.products = data; }, SET_LOGIN_USER(state, u) { state.user = u; } } const actions = { LOAD_PRODUCTS({ commit }) { api.Select().then(res => { commit('INIT_PRODUCTS', res.data); }) }, LOGIN({ commit }, user) { return userApi.Select().then(res => { let users = res.data;//所有的使用者 for (let u of users) { if (u.name == user.name && u.password == user.password) { commit('SET_LOGIN_USER', u); return u; } } }) }, REGISTER({ commit }, user) { return userApi.Insert(user).then(res => { console.log(res.data); return 'OK'; }).catch(err => { return err; }) } } const getters = { ALL_PRODUCTS(state) { return state.products; }, GET_PRODUCT_BYID: (state) => function (id) { //遍歷 is == id for (let p of state.products) { if (p.id == id) { return p; } } return null; } } //倉庫 const store = new Vuex.Store({ state: state, mutations: mutations, actions: actions, getters: getters }) export default store;