什么是Vuex?
VUEX是Vue配套的公共数据管理工具,我们可以将共享的数据保存到vuex中,方便程序中的任何组件中都可以获取和修改vuex中保存的公共数据。
Vuex可能使用的场合
1.在企业级开发中,子组件如果想要使用祖先组件中的数据,就需要一层层的传递,过程十分麻烦
2.兄弟组件之间不能直接传递数据,如果兄弟组件之间想要传递数据就必须借助父组件
state
相当于组件中的data,专门用于保存共享数据
<body>
<div id="root">
<father></father>
</div>
<template id="father">
<div>
<!-- 固定句式调用this.$store.state.xx-->
<h2>{{msg}}{{this.$store.state.year}}</h2>
</div>
</template>
</body>
<script>
const store = new Vuex.Store({
state:{
year:1024
}
})
Vue.component('father',{
template:'#father',
//只要祖先保存了state,那么祖先组件和后代都可以使用其中的共享数据
store,
data() {
return {
msg:'hello'
}
},
})
new Vue({
el:'#root'
})
</script>
mutations
存放修改state内容的方法
<body>
<div id="root">
<father></father>
</div>
<template id="father">
<div>
<h2>{{msg}}{{this.$store.state.year}}</h2>
<button @click="addyear">year+1</button>
</div>
</template>
</body>
<script>
const store = new Vuex.Store({
state:{
year:1024
},
//使用mutations主要是因为直接在组件中对state做修改时,发生错误不容易定位到发生错误的组件。
mutations:{
add(state){
return state.year = state.year+1
}
}
})
Vue.component("father",{
template:'#father',
store,
data() {
return {
msg:'hello',
}
},
methods: {
addyear(){
//固定句式this.$store.commit('mutations里面方法的名字')
this.$store.commit('add')
}
},
})
new Vue({
el:'#root'
})
</script>
getters
和Vue的计算属性的使用差不多
<body>
<div id="root">
<father></father>
</div>
<template id="father">
<div>
<!-- 固定句式调用{this.$store.getters.方法名 -->
<h2>{{this.$store.getters.play}}</h2>
<h2>{{this.$store.getters.play}}</h2>
<h2>{{this.$store.getters.play}}</h2>
</div>
</template>
</body>
<script>
const store = new Vuex.Store({
state:{
name:'world'
},
mutations:{
},
getters:{
play(state){
console.log('我被调用了');//多次调用时,只会输出一次
return state.name+'VUE'
}
}
})
Vue.component("father",{
template:'#father',
store,
data() {
return {
msg:'hello'
}
},
})
new Vue({
el:'#root',
})
</script>