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)站的支持!
相關文章
nuxt 實現(xiàn)在其它js文件中使用store的方式
這篇文章主要介紹了nuxt 實現(xiàn)在其它js文件中使用store的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11詳解探索 vuex 2.0 以及使用 vuejs 2.0 + vuex 2.0 構建記事本應用
本篇文章主要介紹了詳解探索 vuex 2.0 以及使用 vuejs 2.0 + vuex 2.0 構建記事本應用 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06解決Mint-ui 框架Popup和Datetime Picker組件滾動穿透的問題
這篇文章主要介紹了解決Mint-ui 框架Popup和Datetime Picker組件滾動穿透的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue2.0 slot分發(fā)內(nèi)容與props驗證的方法
本篇文章主要介紹了Vue2.0 slot分發(fā)內(nèi)容與props驗證的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12關于vue中ref的使用(this.$refs獲取為undefined)
這篇文章主要介紹了關于vue中ref的使用(this.$refs獲取為undefined),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03vue3 element plus中el-radio選中之后再次點擊取消選中問題
這篇文章主要介紹了vue3 element plus中el-radio選中之后再次點擊取消選中問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08