網(wǎng)站建設(shè)公司前景如何在百度上營銷
實(shí)現(xiàn)組件全局(數(shù)據(jù))管理的一種機(jī)制,可以方便的實(shí)現(xiàn)組件之間共享數(shù)據(jù),不同于上述三種傳遞值的方式。
可以把vuex當(dāng)成一個(gè)store倉庫,可以集中管理共享的數(shù)據(jù),并且存儲(chǔ)在vuex中的數(shù)據(jù)都是響應(yīng)式的,數(shù)據(jù)與頁面同步。
一般情況下,只有組件之間共享的數(shù)據(jù),才有必要存儲(chǔ)到vuex中;對(duì)于組件中的私有數(shù)據(jù),依舊存儲(chǔ)在組件自身的data中。
注意:如果你使用的是HBuilderX,它已經(jīng)內(nèi)置了Vuex。如果你是使用npm或者yarn,可以通過以下命令安裝:
安裝vuex:
npm install vuex --save
1、創(chuàng)建Vuex的store:
在項(xiàng)目的src目錄下創(chuàng)建一個(gè)store文件夾,然后在該文件夾中創(chuàng)建一個(gè)index.js文件,用于定義和配置Vuex store。
/* // 方式一import { createStore } from 'vuex';export default createStore({state() {return {count:0,// 定義一個(gè)名為 name 的狀態(tài)//公共的變量,存儲(chǔ)數(shù)據(jù),這里的變量不能隨便修改,只能通過觸發(fā)mutations的方法才能改變};},mutations: {increment(state) {// 定義一個(gè)名為 increment 的修改狀態(tài)方法state.count++;}//相當(dāng)于同步的操作},actions: {increment({ commit }) {commit('increment');}//相當(dāng)于異步的操作,不能直接改變state的值,只能通過觸發(fā)mutations的方法才能改變},getters: {count: (state) => state.count},}); */
// 方式二 推薦
import Vuex from 'vuex';
import {LoginPostMethod} from '@/api/api.js';const store = new Vuex.Store({state: {count:0,// 定義一個(gè)名為 name 的狀態(tài)resToken: '',// 定義token//公共的變量,存儲(chǔ)數(shù)據(jù),這里的變量不能隨便修改,只能通過觸發(fā)mutations的方法才能改變},mutations: {increment(state) { // 定義一個(gè)名為 increment 的修改狀態(tài)方法state.count ++;},setToken(state,token){// 定義一個(gè)名為 setToken 的修改狀態(tài)方法console.log("state",state);console.log("token",token);state.resToken = token.resToken;uni.setStorageSync('resToken', token.resToken);},setEmptyToken(state){// 定義一個(gè)名為 setEmptyToken 的修改狀態(tài)方法console.log("emptyState",state);state.resToken = '';uni.setStorageSync('resToken', null);},//相當(dāng)于同步的操作},actions: {// 網(wǎng)絡(luò)請(qǐng)求async logIn(context,apyload){console.log("context",context);console.log("apyload",apyload);const res = await LoginPostMethod(apyload)console.log('執(zhí)行成功',res)if(res.success){const token = {resToken: res.token,}// 設(shè)置tokencontext.commit('setToken', token)}// 返回值return res;},//相當(dāng)于異步的操作,不能直接改變state的值,只能通過觸發(fā)mutations的方法才能改變}})export default store
?
2、在main.js中引入store并使用:
3.使用
import store from '@/store/index.js';//需要引入store***
export default{data(){return{}},methods:{addCountMethod() { // 定義一個(gè)名為 addMethod 的增加 count 的方法// 修改狀態(tài)方法store.commit('increment');// 獲取 state 中的 count 值const curcount = store.state.count;console.log("curcount",curcount);}, setMethodOne(){// 直接調(diào)用/store/index.js mutations中定義的方法store.commit("setEmptyToken");},setMethodTwo(){// 調(diào)用/store/index.js 中l(wèi)ogIn方法const result = await store.dispatch('logIn', res)},}
}