Vuex 笔记

官方学习链接:https://vuex.vuejs.org/zh/

 

项目结构:

https://vuex.vuejs.org/zh/guide/structure.html

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块

思路:

1.mutation改变state的状态

2.action commit mutaion

3. store.dispatch.action

 

代码:

代码学习例子:

https://github.com/vuejs/vuex/blob/dev/examples/counter/store.js

 

main.js

全局引入vuex

import store from './store/index'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app');

index.vue

使用vuex:

<template>
    <div class="index footerUpdate" v-cloak style="padding: 100px;">
      <button @click="addCount">
      	点击增加次数
      </button>
      <h1>
      	{{ count }}
      </h1>
    </div>
</template>
<script>

export default {
  data() {
  	return {
  		// count: this.$store.state.count //这里没办法双向绑定
  	}
  },
  computed: {
    count () {
      return this.$store.state.count //要这样才会动态变化
    }
  },
  methods: {
  	addCount() {
  		this.$store.dispatch('increment') // 1.分发
  	}
  }
}
</script>

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import common from './modules/common'
import location from './modules/location'

Vue.use(Vuex);

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

 

state.js

export default {
	count: 1
}

 mutations.js

export default {
	increment(state) {
		state.count++
	}
}

actions.js

export default {
	increment({commit}) {
		commit('increment')
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值