用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
})