npm add vuex 下载vuex
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
name:jing,
age:18,
look:beautiful
},
mutations:{},
actions:{}
})
组件一:
<div>
name:{{username}}
<button @click="add"> 确认</button>
</div>
data(){
return(){
//注意 写在data中,因为先赋值给了username,那么store值如有改变,这里将不能发生改变
// username:this.$store.state.name
}
},
computed:{
username(){
return this.$store.state.name
}
}
methods:{
add(){
this.$store.state.name = 'jing+1'
}
}
组件二:
<div>
name02:{{$store.state.name}}
</div>
但如果sore中有许多的值需要获取就得写很多的 return,有没有更方便的办法呢?
在组件中引入 mapState:
import {mapState} from 'vuex'
//1
computed:mapState(['name','age','look']),
//2
computed:mapState({
storeName:state => state.name,
storeAge:state => state.age,
storeLook:state => state.look
})
//但computed也有自己的运算函数,就不能写1、2这样了
computed:{
...mapState({
storeName:state => state.name,
storeAge:state => state.age,
storeLook:state => state.look
})
}
<div>
name:{{storeName}}
age:{{storeAge}}
look:{{storeLook}}
</div>
.
案例:组件一 点击确定将输入框的内容添加到组件二中。
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
studentList:[]
},
mutations:{},
actions:{}
})
组件一:
<div>
name:
<input type="text" v-model="name">
<button @click="add"> 确认</button>
</div>
export default({
data(){
return(){
name:''
}
}
methods:{
add(){
this.$store.state.studentList.push(this.name);
}
}
})
组件二:
<div>
namelist:
<ul>
<li v-for="(item, index) in studentList" :key="index">
{{item}}
</li>
</ul>
</div>
import {mapState} from 'vuex'
export default({
computed:{
...mapState(['studentList'])
}
})