说明
【Vue 开发实战】学习笔记。
核心概念
State一this.$store.state.xxx 取值
Getter 一this.$store.getters.xxx 取值
Mutation 一this.$store.commit( "xxx" )赋值
Action 一 this.$store.dispatch( "xxx" )赋值
Module
底层原理
- State:提供一个响应式数据
- Getter:借助 Vue 的计算属性 computed 来实现缓存
- Mutation:更改 state 方法
- Action:触发 mutation 方法
- Module:
Vue.set
动态添加 state 到响应式数据中
实现一个 mini-vuex
主要实现响应式:mini-vuex.js
import Vue from 'vue' const Store = function Store (options = {}) { const {state = {}, mutations={}} = options // 核心就是使用了vue的响应式数据 this._vm = new Vue({ data: { $$state: state }, }) this._mutations = mutations } Store.prototype.commit = function(type, payload){ if(this._mutations[type]) { this._mutations[type](this.state, payload) } } Object.defineProperties(Store.prototype, { state: { get: function(){ return this._vm._data.$$state } } }); export default {Store}
App.vue
<template> <div id="app"> <h1>count:{{count}}</h1> <button @click="$store.commit('increment')">min-vuex--commit:count++</button> </div> </template> <script> export default { name: 'app', computed: { count() { return this.$store.state.count } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
main.js
import Vue from 'vue' import Vuex from './min-vuex' import App from './App.vue' Vue.use(Vuex) Vue.config.productionTip = false const store = new Vuex.Store({ state: { count: 0, }, mutations: { increment(state) { state.count++ } } }) Vue.prototype.$store = store new Vue({ render: h => h(App), }).$mount('#app')
发现也是ok的