vuex使用規則

2021-08-17 20:06:21 字數 2113 閱讀 4456

下面利用webpack搭建平台。

import vue from 'vue'

import vuex from 'vuex'

import index from './index.vue'

vue.use(vuex);

const store = new vuex.store(,]}

});var root = document.createelement('div');

new vue().$mount(root);

this.$store.state.count;
在子元件中對store.state值的改變會同步體現在其他元件中。

const store = new vuex.store(,]},

mutations: ,

decrease(state)

}});

mutations中是對state資料進行統一操作,方便記錄資料變化,不允許在子元件中直接操作state,雖然這樣操作可以改變state值,但不推薦。

同時mutations中的操作都是同步的。

this.$store.commit('increment',5);

this.$store.commit('decrease');

const store = new vuex.store(,]},

actions:,obj),1000)})}

}});

countadd() ).then(function (data) )

}

const store = new vuex.store(,]},

getters:);}}

});

this.$store.getters

.donetodos

;

import  from

'vuex'

import from

'vuex'

import from

'vuex'

export default ),

...mapgetters()

},methods: )

} }

這裡需用配置babel以解析擴充套件運算子。

webpack.config.js中新增js解析loader

,
配置.babelrc檔案

}],"stage-3" // 一定不要忘記

],"plugins": ["transform-runtime"]

}

安裝以下依賴

"babel": "^6.23.0",

"babel-core": "^6.26.0",

"babel-loader": "^7.1.4",

"babel-plugin-transform-runtime": "^6.23.0",

"babel-preset-env": "^1.6.1",

"babel-preset-es2015": "^6.24.1",

"babel-preset-stage-3": "^6.24.1",

此時可在子元件中直接引用。

show count mapstate countalias:

}p>

show count done todos:

}p>

type="button" @click="incrementasync()"

value="increase aysnc">

Vuex使用記錄

最近在專案上使用vuex,從陌生到熟悉,整理一下使用思路和方法,加深印象。官方文件 先明確幾個概念 1.state 資料來源 訪問 this.store.state.x2.getter vuex的計算屬性。類似於computed裡面的操作函式。如果要在多個元件使用,提取到getter中,就會十分方便...

vuex基本使用

使用vuex 1.安裝vuex,搭建手腳架 npm i vuex s2.建立乙個store資料夾,在該資料夾中建立乙個index.js檔案 2.1引入相應的檔案 import vue from vue import vuex from vuex 2.2使用vuex vue.use vuex 3.建立...

vuex基本使用

1.首先要在store index.js檔案配置vuex vuex基本有state 用來定義共享狀態,actions 實現非同步請求操作,mutations 存放了所有更改狀態的方法,getters 類似於計算屬性,根據vuex的state狀態派發乙個新的狀態出來.自己封裝的ajax請求 vue.u...