欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

vuex的state状态对象使用方式汇总

程序员文章站 2022-03-18 23:36:30
...
这次给大家带来vuex的state状态对象使用方式汇总,vuex的state状态对象使用注意事项有哪些,下面就是实战案例,一起来看一下。

下面给大家来贴一下我的vuex的结构

下面是store文件夹下的state.js和index.js内容

//state.js
const state = {
 headerBgOpacity:0,
 loginStatus:0,
 count:66
}
export default state
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import actions from './actions'
import getters from './getters'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
 state,
 actions,
 getters,
 mutations
})

下面开始在test.vue组件当中使用vuex的state状态对象

方式一

<template>
 <p class="test">
  {{$store.state.count}} <!--第一种方式-->
 </p>
</template>
<script type="text/ecmascript-6">
 export default{
  name:'test',
  data(){
   return{ }
  }
 }
</script>
<style>
</style>

方式二

<template>
 <p class="test">
  {{count}} <!--步骤二-->
 </p>
</template>
<script type="text/ecmascript-6">
 export default{
  name:'test',
  data(){
   return{}
  },
  computed:{
   count(){
    return this.$store.state.count; //步骤一
   }
  }
 }
</script>
<style>
</style>

方式三

<template>
 <p class="test">
  {{count}} <!--步骤三-->
 </p>
</template>
<script type="text/ecmascript-6">
 import {mapState} from 'vuex' //步骤一
 export default{
  name:'test',
  data(){
   return{}
  },
  computed:mapState({     //步骤二,对象方式
   count:state => state.count
  })
 }
</script>
<style>
</style>

方式四

<template>
 <p class="test">
  {{count}} <!--步骤三-->
 </p>
</template>
<script type="text/ecmascript-6">
 import {mapState} from 'vuex' //步骤一
 export default{
  name:'test',
  data(){
   return{}
  },
  computed:mapState([    //步骤二,数组方式
   "count"
  ])
 }
</script>
<style>
</style>

方式五

<template>
 <p class="test">
  {{count}} <!--步骤三-->
 </p>
</template>
<script type="text/ecmascript-6">
 import {mapState} from 'vuex' //步骤一
 export default{
  name:'test',
  data(){
   return{}
  },
  computed:{
   ...mapState([       //步骤二,三个点方式
    "count"
   ])
  }
 }
</script>
<style>
</style>

相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!

推荐阅读:

使用ES6中class模仿Vue做出双向绑定

怎样操作vue进行数据传递

以上就是vuex的state状态对象使用方式汇总的详细内容,更多请关注其它相关文章!