一、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>