vuex 是什么
官方文档:

vuex 要解决什么问题
官方文档:


也就是说,开发大型单页应用的时候使用 vuex 能够更好地解决问题
用 vue 去类比 vuex
我们用 vue 去类比 vuex 会更加的好理解一点,这里借用 通俗理解vuex原理---通过vue例子类比 这篇文章来解读
先来看一个简单的 vue 响应式的例子
vue 中的 data 、methods、computed 三者可以实现响应式
- 视图通过点击事件,触发 methods 中的 increment 方法
 - 该方法更改 data 中 count 的值
 - 一旦 count 值发生变化,computed 中的函数能够把 getCount 更新到视图
 
    <template>
      <div id="app">
        <button @click="increment"></button>
        {{getCount}}
      </div>
    </template>
    
    <script>
    new Vue({
        el: "#app",
        // state
        data () {
         return {
            count: 0
         }
        },
        
        // actions
        methods: {
         increment () {
            this.count++
         }
        },
        
         // view
        computed: {
          getCount(){
            return this.count
          }
        },
    })
    </script>
用 vuex 来实现同样的功能
二者类比如下:

然后用 vuex 来实现以上的功能:
- 视图通过点击事件,触发 mutations 中的 increment 方法
 - 该方法更改 state 中 count 的值
 - 一旦 count 值发生变化,getters 中的函数能够把 getCount 更新到视图
 
我们看官网的图片:

另外的 action、dispatch、commit 是干嘛的?
- action 可以理解是为了处理异步而多加的一层
 - 组件通过 dispatch 可以触发 actions 中的方法
 - actions 中的 commit 可以触发 mulations 中的方法
 
用 vuex 实现的代码:
store.js
        const store =  new Vuex.Store({
        state: {
            count: 0
        },
        mutations: {
            incrementMutations(state) {
            	return state.count++
            }
        },
            
        actions: {
            incrementActions({commit}) {
            	commit("incrementMutations"); 
            }
         
        },
        
        //通过getter中的方法来获取state值
        getters: {
            getCount(state) {
            	return state.count
            }
        }
        })
         
        export default store
main.js
        import Vue from 'vue'
        import App from './App.vue'
        import store from './store'
         
        Vue.config.productionTip = false
         
        new Vue({
          store,
          render: h => h(App)
        }).$mount('#app')
APP.store
       <template>
       <div id="app">
           <div id="app">
               <button @click="incrementClick">增加</button>
               {{this.$store.getters.getCount}}
           </div>
       </div>
       </template>
        
       <script>
       export default {
           methods: {
             incrementClick(){
               this.$store.dispatch("incrementActions")
             }
           }
       }
       </script>
参考文章
- Vuex 官方文档
 - 通俗理解vuex原理---通过vue例子类比
 
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
 - 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
 
- 提示下载完但解压或打开不了?
 
- 找不到素材资源介绍文章里的示例图片?
 
- 模板不会安装或需要功能定制以及二次开发?
 
                    
    
发表评论
还没有评论,快来抢沙发吧!