1核心概念是定义一个状态管理(state),与main.js同级建立一个store.js,将state放在里面
2 创建store.js,在里面写state
export default{ // 状态 state:{ message:'store data', }, // 通过方法形式来操作state而不是直接操作 setStateMessage(str){ this.state.message = str; } }
3 BrotherList组件和SisterList组件是兄弟组件,这两个组件都要在App.vue组件中显示所以相对而言App组件是这两个组件的父组件
3.1 在App组件中引入BrotherList组件和SisterList组件,结果是将这两个组件里的数据展示在页面上因为App是最外层组件,而页面显示的是App组件,所有数据不可能只写在App组件里面,要想在App组件里面显示其他组件内容必须将其他组件引入App组件中,也可以理解为App组件是所有组件的父组件。
4 BrotherList组件和SisterList组件拿取store中的数据
4.1// 1 引入store.js
import store from "../store"
4.2将store中的state拿出来并赋值命名为state
export default { data(){ return{ // 2 将store中的state拿出来并赋值命名为state state:store.state } } }
4.3展示store中的数据,需要的是store中的message,这里的store等于下面return中的store -->
{{state.message}}
5兄弟组件数据传递(从store中拿到数据了,可以更改啊)在BrotherList组件中定义一个按钮,点击按钮可以更改store中的message当然SisterList组件中的数据也会更改因为数据是从store中拿到的而store中的数据已经被更改了
5.1
brotherlist copmonents改变store中的数据
## 5.2 methods:{ // 2 更改store中的数据函数 changeData(){ console.log(this.state) // 改变store中的数据,通过上面引入的store,调用它的setStateMessage方法并给他传参,参数是你要改成的数据 // 整体通过调用store中的函数来修改store中的数据而不是直接对store中的数据更改 store.setStateMessage("new store data") } }