state 儲存數(shù)據(jù)
<!-- 1. 在store 文件下 創(chuàng)建 state.js -->
目錄:
store
|-- modules
|-- index.js
|-- state.js
<!-- 2. state.js ------------- -->
<script>
const state = {
Title: "Vuex state"
}
export default state;
</script>
<!-- 3. index.js --------------- -->
<script>
// ...
import state from "./state.js"
// ...
const store = new Vuex.Store({
// ...
state // state => state: state
})
export default store;
</script>
<!-- 4. 組件中使用: -->
<script>
export default {
// 計算屬性
computed: {
Title(){
return this.$store.state.Title
}
}
}
</script>
<!-- 5. mapState 輔助函數(shù) -->
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
Title: state => state.Title,
// 傳字符串參數(shù) 'Title' 等同于 `state => state.Title`
TitleContent: 'Title'
})
}
}
</script>