cnpm install vuex -S
步驟一:先定義vuex核心的文件夾 store 并在里面加入 index.js
1、不使用 modules 的情況下,所有的文件都在 index.js中定義
state 定義字段,類似我們的頁面的data
actions 這個階段用來請求后臺數(shù)據(jù),然后把后臺數(shù)據(jù)給發(fā)送到 mutations 函數(shù)方法里面
mutations 可以做邏輯操作,跟 methods 一樣
getters 將state里面定義的字段發(fā)送出去
store->index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//1 定義字段,類似我們的頁面的data
state: {num: 10,goods: []},
//3 這個階段是可以做邏輯操作,跟 methods 一樣 //這里的調(diào)用有兩種,
(1)actions里面調(diào)用,commit('mutations里面定義的方法名',具體的參數(shù))
(2)頁面上通過 this.$store.commit('mutations里面定義的方法名',具體的參數(shù))
mutations: {
mAdd(state, count) {console.log(state,count);state.num = state.num + count},
addShopping(state, name) {state.goods.push(name)}
},
//2 一般情況不用這個,這個階段用來請求后臺數(shù)據(jù),然后把后臺數(shù)據(jù)給發(fā)送到 mutations 函數(shù)方法里面
actions: {
// 至少要有一個參數(shù),context上下文對象,觸發(fā)mutations中函數(shù)執(zhí)行,或者直接改state中數(shù)據(jù)都可以
add(context, count) {
// 使用commit,觸發(fā)mutations中得函數(shù)
// console.log(context,count)
context.commit('mAdd', count) // 會觸發(fā)mutations中得mAdd的執(zhí)行
},
addShopping(context, name) {//下面的注釋是偽代碼
// 1.這里起ajax請求,檢查name庫存夠不夠,2.假設(shè)庫存不夠,彈個不夠的消息,3.alert('庫存不夠了')
// 4.return
context.commit('addShopping', name)
} }})
步驟二:在main.js中引入store,然后可以在頁面用 this.store來調(diào)用store
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'///////////////////////////////////////////////////////////////////
import Vuex from "vuex"; // 引入vuex核心庫////////////////////////////////////////////////
import elementui from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Vuex) // 應(yīng)用Vuex插件 也就是將Vuex插件加入到Vue對象的對象屬性中
Vue.config.productionTip = false
Vue.use(elementui)
new Vue({
router,
store,//////////////////////////////////////////////////////////////////////////////////////
render: h => h(App)
}).$mount('#app')
步驟三:在具體頁面上使用(帶modules的),比如HomeView.vue頁面
views->HomeView.vue
<template>
<div class="home">
<h1>1 vuex的使用 -基本使用(操作state的數(shù)據(jù))</h1>購物車商品數(shù)量:{{ $store.state.num }}
<br><button @click="handleAdd">點我加購物增1</button>
<h1>組件間通信</h1>
<ul><li>蘋果<button @click="add('蘋果')">+</button></li><li>桃子<button @click="add('桃子')">+</button></li><li>梨<button @click="add('梨')">+</button></li></ul>
<br><ShppingCard></ShppingCard>
</div>
</template>
<script>import ShppingCard from "@/components/ShppingCard";
export default {
name: 'HomeView',data() {return {}},
methods: {
handleAdd() {
// this.$store.state.num += 1// 1 直接操作
// this.$store.dispatch('add', 2) //add 必須是action中得函數(shù)// 2 正統(tǒng)方式,通過dispatch觸發(fā)actions
this.$store.commit('mAdd', 3)// 3 直接操作mutations
},
add(name) {
// this.$store.state.goods.push(name)// 1 直接操作
this.$store.dispatch('addShopping', name)// 2 正常套路
} },
components: {ShppingCard} }
</script>
components->ShppingCard.vue
<template><div>購物車商品:{{ $store.state.goods }}</div></template>
<script>export default {name: "ShppingCard"}</script>