####一、vuex安装好后,默认已经注册到全局
main.js引入
注册
####二、在store文件夹,index.js中
export default new Vuex.Store({
//state => 存储初始化数据 this.$store.state.flag 获取
state:{
flag:true,
todos: [
{ id: 1, text: '写作业', done: true },
{ id: 2, text: '运动', done: false }
]
},
//getters => 相当于计算属性computed;也可以对state的数据进行二次过滤(类似于filter)
//下面的doneTodos,是对state的数据todos进行二次过滤
getters:{
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
},
//mutations => 更改state里数据的唯一方法
//在test1.vue页面中触发事件时候,在事件函数种中使用 this.$store.commit('SET_FLAG')
mutations:{
SET_FLAG(state) {
state.flag= !state.flag
//console.log(state.flag)
},
},
actions:{
},
modules:{
}
})
#####test1.vue
<template>
<div>
<button @click="changeState">按钮</button>
</div>
</template>
<script>
import {ref,reactive,computed} from '@vue/composition-api';
export default {
setup(props,{root}){
const changeState = ()=>{
root.$store.commit('SET_FLAG');
}
}
}
</script>