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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

VueX的store的简单使用心结

發(fā)布時間:2023/12/13 vue 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 VueX的store的简单使用心结 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

vuex的特點:

多組件共享狀態(tài): 多個組件使用同一個數(shù)據(jù)
任何一個組件發(fā)生改變, 其他組件也要跟著發(fā)生相應(yīng)的變化

安裝vuex npm install vuex:

創(chuàng)建實例:

import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex)const state = {name : '張三',age : 18 } const mutations = {// 更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutationchangeName (state, params) {state.name = params.name},changeAge (state, params) {state.age = params.age} } const actions = {// Action 函數(shù)接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調(diào)用 context.commit 提交一個 mutationactionsChangeAge ( context, params) {context.commit('changeAge', params)} } const getters = {// Getter 接受 state 作為其第一個參數(shù)doubleAge (state) {return state.age * 2}// 也可以使用箭頭函數(shù)的簡寫// doubleAge: state => state.age * 2 }const store = new Vuex.Store({ // 創(chuàng)建全局狀態(tài)管理的實例state, // 共同維護的全局狀態(tài)mutations, // 處理數(shù)據(jù)的唯一途徑, 修改state的數(shù)據(jù)只能通過mutationsactions, // 數(shù)據(jù)的異步操作處理getters // 獲取數(shù)據(jù)并渲染 })// 導(dǎo)出并在main.js里面引用&注冊 export default store# 引入文件: import Vue from 'vue' import App from './App.vue' import store from './store/index' Vue.config.productionTip = falsenew Vue({store, // 全局使用render: h => h(App), }).$mount('#app')# 模板:<template><div><h2>組件</h2><!-- 組件可以通過this.$store.state 獲取store中的數(shù)據(jù) -->name: {{ this.$store.state.name }} <br>age: {{ this.$store.state.age }}<button @click="change">修改年齡</button></div> </template> <script> export default {methods: {change () {// 此方法一般用于網(wǎng)絡(luò)請求// dispatch: 調(diào)用actions里面的方法, 再讓actions里面的方法// 通過commit 調(diào)用mutations里面的方法this.$store.dispatch('actionsChangeAge', { age: 120 })},changeName () {// 通過$store.commit直接調(diào)用store實例中mutation里面的方法// 參數(shù)1: 要調(diào)用mutation里面的方法名, 參數(shù)2: 要傳輸?shù)臄?shù)據(jù)this.$store.commit('changeName', { name: '寶寶', age: 19})}} } </script> ----------------------------------------------------------------// 以載荷形式 store.commit('increment'{amount: 10 //這是額外的參數(shù) })// 或者使用對象風(fēng)格的提交方式 store.commit({type: 'increment',amount: 10 //這是額外的參數(shù) })dispatch:含有異步操作,數(shù)據(jù)提交至 actions ,可用于向后臺提交數(shù)據(jù) this.$store.dispatch('isLogin', true);commit:同步操作,數(shù)據(jù)提交至 mutations ,可用于讀取用戶信息寫到緩存里 this.$store.commit('loginStatus', 1);state 存放基本數(shù)據(jù) getters 從state基本數(shù)據(jù)派生出的數(shù)據(jù)(類似vue中的computed) mutations Store中更改state數(shù)據(jù)狀態(tài)的唯一途徑 actions 通過dispatch觸發(fā)actions, actions在通過commit觸發(fā)mutations。一般用于處理異步操作 modules 模塊化Vuex

總結(jié)

以上是生活随笔為你收集整理的VueX的store的简单使用心结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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