- 全局安裝vuex
npm install vuex --save-dev
- 建立獨(dú)立文件
import Vue from 'vue'
import Vuex,{mapState} from "vuex"
Vue.use(Vuex);
let store = new Vuex.Store({
state:{
list:[{name:"mazhenxiao",id:1,value:"mazhenxiao@gmailcom"}]
},
mutations:{
setdata(state,arg){
console.log(arg);
}
}
})
export {store,mapState}
- 在頁面導(dǎo)入,本例子是在vue-cli中測試唯灵,發(fā)現(xiàn)一直報錯对途,報錯插件為eslint-loader份蝴,果斷在build文件下的webpack.base.conf.js中注釋掉改插件骂远,程序順利跑起來刻恭。
<template>
<div class="hello">
<h2>Essential Links</h2>
<ul>
<li v-for="li in list" @click="eventclick(li)">{{li.name}}</li>
</ul>
</div>
</template>
<script>
import {store,mapState} from "@/router/setvuex"
export default {
name: 'hello',
store,
computed:mapState({
list:state=>state.list
}),
methods:{
eventclick(arg){
arg.id+=1;
arg.name+=arg.id
this.$store.commit("setdata",arg)
}
}
}
</script>
總結(jié)如下:
vuex為多模塊統(tǒng)一數(shù)據(jù)源解決方案佛玄,在當(dāng)前componet中綁定數(shù)據(jù)時應(yīng)綁定到computed中硼一,并給當(dāng)前模塊綁定vuex實(shí)例,在有需要改動數(shù)據(jù)源中使用 this.$store.commit("xxx",{xxx});方式觸發(fā)mutations梦抢,并更新view層般贼。