vue vuex學(xué)習(xí)

用vuex的好處

1、解決了不同組件的數(shù)據(jù)共享問題
2、組件里面的數(shù)據(jù)持久化

環(huán)境及項(xiàng)目搭建

下載node.js,安裝之后在cmd里輸入命令行
npm install webpack -g
安裝vue-cli,輸入命令行
npm install webpack -g vue-cli
使用命令 vue init webpack vue-demo 搭建vue項(xiàng)目, vue-demo”是你的項(xiàng)目名稱。

安裝vuex

使用命令:npm install vuex --save

vuex的使用

1、在src的目錄下新建一個(gè)vuex的文件夾
2、在vuex下面新建一個(gè)store.js
直接把store.js里的代碼貼上,里面有注釋

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

//創(chuàng)建存儲(chǔ)數(shù)據(jù)的倉(cāng)庫(kù)state,集中管理數(shù)據(jù),相當(dāng)于data,用語存儲(chǔ)數(shù)據(jù)
const state={
     msg:"這是測(cè)試的",
     count:1,
     list:[]
}

//actions中的方法,這里面的方法都是異步操作
//頁面上調(diào)用這個(gè)里面的方法,其實(shí)還是調(diào)用的下面mutations里的方法
//頁面上調(diào)用這個(gè)里面的方法使用this.$store.dispatch()
const actions={
     setValue(context,res) {
        // console.log(res);
        context.commit('setData',res);
     }

}

//創(chuàng)建mutations,主要放的是方法,目的是能最終改變倉(cāng)庫(kù)中的數(shù)據(jù),這里是同步操作
//頁面上調(diào)用這里的方法使用this.$store.commit()
const mutations={
     //如果要傳值必須加一個(gè)state
    setData(state,result) {
      state.msg=result;       
    },
    addcount(){
         ++state.count
    },

    //給list賦值
    setLlist(state,result){
         console.log("hhh"+result.length);
         state.list = state.list.concat(result);
    }
}   

//有點(diǎn)類似于計(jì)算屬性  改變state里的count的值的時(shí)候會(huì)觸發(fā)這里面的方法
const getters={
     computedcount:(state)=>{
          return state.count*2;
     }
}

//暴露出去,實(shí)例化
export default new Vuex.Store({
state,
actions,
mutations,
getters

})

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容