vuex的簡單使用教程
什么是Vuex?
vuex是一個專門為vue.js設計的集中式狀態(tài)管理架構。狀態(tài)?我把它理解為在data中的屬性需要共享給其他vue組件使用的部分,就叫做狀態(tài)。簡單的說就是data中需要共用的屬性。
使用vuex進行組件間數(shù)據(jù)的管理
npm i vuex -S
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store.js'
new Vue({
store,
el: '#app',
render: h => h(App)
})
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 這里定義初始值
let state = {
count:10
};
const mutations = {
add(context){
context.count++
},
decrease(context){
context.count--
}
};
// 事件觸發(fā)后的邏輯操作
// 參數(shù)為事件函數(shù)
const actions = {
add(add){
add.commit('add')
},
decrease(decrease){
decrease.commit('decrease')
},
oddAdd({commit,state}){
if (state.count % 2 === 0) {
commit('add')
}
}
};
// 返回改變后的數(shù)值
const getters = {
count(context){
return context.count
},
getOdd(context) {
return context.count % 2 === 0 ? '偶數(shù)' : '奇數(shù)'
}
};
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
App.vue
<template>
<div id="app">
<button @click="add">add</button>
<button @click="decrease">decrease</button>
<button @click="oddAdd">oddAdd</button>
<div>{{count}}</div>
<div>{{getOdd}}</div>
</div>
</template>
<script>
import {mapGetters,mapActions} from 'vuex'
export default {
// 得到計算后的值
computed:mapGetters(['count','getOdd']),
// 發(fā)生點擊事件觸發(fā)不同函數(shù)
methods:mapActions(['add','decrease','oddAdd'])
}
</script>

GitHub: https://github.com/wmui
總結
以上所述是小編給大家介紹的vuex的簡單使用教程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
第一次使用webstrom簡單創(chuàng)建vue項目的一些報錯實戰(zhàn)記錄
在使用webstorm新建vue項目時常會遇到一些報錯,特別是新手第一次運行項目,這篇文章主要給大家介紹了關于第一次使用webstrom簡單創(chuàng)建vue項目的一些報錯實戰(zhàn)記錄,需要的朋友可以參考下2023-02-02
Vue修改iview組件的樣式的兩種方案(element同)
使用vue必然會用到等iview組件庫,但是iview的組件的樣式跟自己寫的div的樣式修改不太一樣,所以本文給大家介紹了Vue修改iview組件的樣式的兩種方案(element同),需要的朋友可以參考下2024-04-04
vue3子組件如何修改父組件傳過來的props數(shù)據(jù)
周所周知vue的props是單向數(shù)據(jù)流,可以從父組件中改變傳往子組件的props,反之則不行,下面這篇文章主要給大家介紹了關于vue3子組件如何修改父組件傳過來的props數(shù)據(jù)的相關資料,需要的朋友可以參考下2022-10-10

