1.为什么要使用vuex?
以Tab选项卡作为示例
Tab->index.vue
<template>
<div>
<a href="javascript:;"
:class="[{current: curInx == 0}]" @click="changTab(0)"
>选项1</a>
<a href="javascript:;"
:class="[{current: curInx == 1}]" @click="changTab(1)"
>选项2</a>
<a href="javascript:;"
:class="[{current: curInx == 2}]" @click="changTab(2)"
>选项3</a>
<a href="javascript:;"
:class="[{current: curInx == 3}]" @click="changTab(3)"
>选项4</a>
</div>
</template>
<script>
export default {
name: 'Tab',
props:{
curInx: Number
},
methods:{
changTab(index){
this.$emit('changTab',index)
}
}
}
</script>
<style scoped>
a{
margin-right: 10px;
color: aqua;
}
.current{
color: #000;
text-decoration: none;
}
</style>
Page->index.vue
<template>
<div>{{content[curInx]}}</div>
</template>
<script>
export default{
name: 'Page',
props:{
curInx:Number
},
data(){
return{
content:[
'页面1',
'页面2',
'页面3',
'页面4',
]
}
}
}
</script>
<style scoped>
</style>
APP.vue
<template>
<div id="app">
<tab
:curInx = "cueInx"
@changTab="changTab"
/>
<page
:curInx ="cueInx"
/>
</div>
</template>
<script>
import Tab from "@/components/Tab";
import Page from "@/components/Page";
export default{
name: 'App',
components:{
Tab,
Page
},
data(){
return{
cueInx: 0
}
},
methods:{
changTab(index){
console.log(index)
this.cueInx = index
}
}
}
</script>
<style scoped>
#app{
/* background-color: #F8F8FB; */
background-color: #F8F8FB;
height: auto;
}
</style>
从代码中可以看出,点击tab是在父组件app.vue赋值给curInx完成的,tab跟page兄弟组件不能直接传值或者更改值,本应该在子组件操作的逻辑是在父组件完成的,我们希望的是有一个容器去管理这些状态,并且共享给任何组件,容器还装了一些方法,这些方法可以去更改这些状态,组件只需要调用这些方法,去更改数据,那么视图就发生了改变。Vuex就帮我们解决了这个问题。