actions 所有異步操作只能放在actions 中? ??Action 可以包含任意異步操作翘骂。(為了告訴自己的,怕忘記了)
命名空間? ?和? 命名函數(shù)? ?modules 把? store 模塊化? 以后會這么做
https://github.com/wangyess/vue-cli-3/tree/master/src/store
首先下載vuex? 并且建立一個store 文件夾 在建一個store.js? 文件
npm? install vuex --save? ? ?//安裝vuex
在store.js? 文件中? 引入vue? vuex? 并且讓vue使用vuex?
import? Vue form ' vue ';
import Vuex form ' vuex ';
Vue.use( Vuex );
定義store? 并且暴露出去? 以供后續(xù) main.js? 中引入
const store = new Vuex.Store({
?# /* state? ?管理狀態(tài)? 要用的數(shù)據(jù)都在這里? */
? ? state:{? ? ? ? ? ? ??
? ? ? ? ?count:9
? ? }碳竟,
#? /** getters? ?怎么說呢狸臣!? 可以對state中的數(shù)據(jù)進(jìn)行過濾 或者說是添加一些判斷條件啊 比如當(dāng) count=0 的時? ? ? ? ? ?*候可以讓其 顯示為空? 等等!??
? ? ?? *如下面這種? 外部想要訪問count? 就應(yīng)該是這樣的
? ? ?? *this.$store.getters.getcount;? ? ?*/
? ? ?getters:{
? ? ? ? ? getcount( state ){
? ? ? ? ? ? ? ? ? return state.count >0 ? state.count : state.count = 0;
? ? ? ? ?}
? ? },
/*? mutations? 是用來處理數(shù)據(jù)的? 里面定義的都應(yīng)該是方法? 如果外部想要改變數(shù)據(jù)? 只有調(diào)方法
? ? ?通過? ?this.$store.commit(" addcount ");? 不要疑惑為什么方法寫成了字符串? 語法就是這樣
? ? ?注意 : 這個這么調(diào)方法的前提是? ?沒有加? actions??
*/
mutations:{
? ? ? ? addcount(state){
? ? ? ? ? ? ? state.count++;
? ? ? ? }
? ? },
/*? 如果增加 actions? ? 那么外部調(diào)用就應(yīng)該先經(jīng)過actions? 在actions? 中調(diào)用 mutations 中的方法
? ? 但是 actions 并不是必須品? 所以可以直接在外部調(diào)用? mutations 中的方法 统翩,但是加了actions?
? ? 那么外部調(diào)用的方法就變成? this.$store.dispatch(" actionaddcount "); 之后再actions 中調(diào)用
? ? mutations 中的方法? context.commit(" addcount ");
*/
actions:{
? ? ? ?actionaddcount(context){
? ? ? ? ? ? ? context.commit(" addcount ");
? ? ? ?}
? ?}
}
看完上面有可能還沒沒有太懂 我把方法總結(jié)一下? ? ? 我是以上面為例子
不加? getters? ? ? ?外部對數(shù)據(jù)的訪問方法? ?===? 也就是獲取數(shù)據(jù)
this.$store.state.count;
添加? getters? ? ? 外部對數(shù)據(jù)的訪問? ?首先經(jīng)過getters? 在getters? 的方法中對想要的數(shù)據(jù)進(jìn)行處理 并返回
this.$store.getters.getcount;? ?
不加actions? ? ? 外部想要改變數(shù)據(jù)? 調(diào)用的方法? ? ?在mutations 的方法? addcount 中處理數(shù)據(jù)??
this.$store.commit(" addcount ");
添加actions外部想要改變數(shù)據(jù)? 就應(yīng)該先經(jīng)過actions 在actions 的方法?actionaddcount? 中調(diào)用 mutations 中的方法
this.$store.dispatch(" actionaddcount");
actionaddcount? 方法中用??context.commit(" addcount ");? 調(diào)用mutations 中的addcount 方法
覆蓋一個我的代碼吧? 只是方法名有些不一樣
import Vuefrom 'vue';
import Vuexfrom 'vuex';
Vue.use(Vuex);
const store= new Vuex.Store({
? ? ?state:{
? ? ? ? ? count:9此洲;
},
? ? getters:{
? ? ? ? ? gettercount(state){
? ? ? ? ? ? ? ? ?return state.count>0 ? state.count : state.count=0;
? ? ? ?}
},
? ? mutations:{
? ? ? ? ? ?increment(state){
? ? ? ? ? ? ? ? ? state.count++;
? ? ? ? ? },
},
? ? actions:{
? ? ? ? ? ?increment(context){
? ? ? ? ? ? ? ? ? context.commit("increment");
? ? ? ? ? },
}
})
export default store;? ? ?//? 暴露出去? 在main.js? 中? 掛在到new vue? 實例上
在main.js? 中先引入? store.js? 文件??
import store? from './store/store';
之后給你放一個截圖會更清楚一些