日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vuex状态管理简单入门

發(fā)布時間:2025/6/16 vue 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vuex状态管理简单入门 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1.安裝vuex

npm i --save-dev vuex 復制代碼

2.為了方便管理,在src目錄下新建文件夾store

新建index.js進行初始化 新建state.js進行數(shù)據(jù)存儲 新建mutations.js保存數(shù)據(jù)修改的方法 復制代碼

3.開始編寫配置文件

index.js

import Vue from 'vue' import Vuex from 'vuex' import state from './state' import mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({// 存儲數(shù)據(jù)state,// 修改方法mutations }) 復制代碼

在main.js中引入并實例化

import store from '@/store/index' new Vue({el: '#app',router,// 實例化storestore,render: h => h(App) }) 復制代碼

4.到這里vuex已經(jīng)配置完成,只要在state.js中寫入數(shù)據(jù)即可在項目中引用了

state.js

const state = { //這里以常用的用戶id為例,可以是任意你想保存的數(shù)據(jù)userId: '0123456789' } export default state 復制代碼

5.現(xiàn)在你就可以在項目中的任何組件取到用戶id,方法如下(關于map的作用就自己查閱資料吧)

import { mapState } from 'vuex' export default {computed: {...mapState({userId: state => state.userId})},// 然后在你需要的地方使用this.userId即可,如created () {console.log(this.userId)} } 復制代碼

6.關于修改state中屬性的值

還是以用戶id為例,每個用戶保存的值必然是不同的,這個值需要用mutations中的方法來修改

mutations.js

const mutations = { //save_userId是方法名, userId是傳入的修改值save_userId (state, userId) {state.userId = userId} }export default mutations 復制代碼

7.在需要保存用戶id的地方調用mutations中的方法進行保存

import { mapMutations } from 'vuex' export default { // 引入方法save_userId方法methods: {...mapMutations({save_userId: 'save_userId'})} // 保存或修改數(shù)據(jù)created () {this.save_userId('987654321')} } 復制代碼

8.到這里數(shù)據(jù)的存儲也完成了,取數(shù)據(jù)只要用第5步的方法即可,vuex的簡單使用也不復雜,希望剛入門的小伙伴看完有所收獲吧,之后有空在推出與actions相關的部分。

轉載于:https://juejin.im/post/5afcb72a6fb9a07aab2a0c3e

總結

以上是生活随笔為你收集整理的vuex状态管理简单入门的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。