vue3核心概念-State

发布时间 2023-07-13 11:48:12作者: 商品部-林军

image-20220916093727028

Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 ”而存在。这也意味着,每个应用将仅仅包含一个 store 实例

在 Vue 组件中获得 Vuex 状态

import { createStore } from 'vuex'
const store = createStore({
  state:{
    count:10
   }
})
export default store

选项式API

<template>
  <h3>Nums</h3>
  <p>{{ $store.state.count }}</p>
  <p>{{ count }}</p>
</template>
<script>
export default {
  computed:{
    count(){
      return this.$store.state.count
     }
   }
}
</script>

组合式API

<template>
  <h3>Count</h3>
  <p>{{ $store.state.count }}</p>
  <p>{{ count }}</p>
</template>
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const count = computed(() =>{
  return store.state.count
})
</script>

mapState 辅助函数(只能在选项式API中使用)

<template>
  <h3>Nums</h3>
  <p>{{ $store.state.count }}</p>
  <p>{{ count }}</p>
</template>
<script>
import { mapState } from 'vuex'
export default {
  computed:{
    ...mapState(["count"])
   }
}
</script>

实时效果反馈

1. 下列代码,划横线处应该填写的代码是:

<template>
  <h3>Count</h3>
  <p>{{ $store.state.count }}</p>
  <p>{{ count }}</p>
</template>
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = ___
const count = computed(() =>{
  return store.state.count
})
</script>

A vuex

B createStore

C store()

D useStore()

答案

1=>D