vuex的state中的数据的四种使用方法
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 1
}
export default new Vuex.Store({
state,mutations
})
- 直接通过$store来使用
<template>
<div>
<h3>{{msg}}</h3>
<hr/>
<h3>{{$store.state.count}}</h3>
</button>
</div>
</template>
<script>
import store from '@/vuex/store'
export default {
data(){
return{
msg:"hello vuex"
}
},
store
}
</script>
<style>
</style>
- 通过computed添加一个计算属性来使用
<template>
<div>
<h3>{{$store.state.count}}------{{count}}</h3>
<hr/>
</div>
</template>
<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
data(){
return{
msg:"hello vuex"
}
},
computed:{
count(){
return this.$store.state.count
}
},
store
}
</script>
<style>
</style>
- 通过computed+mapState返回函数的方法来使用
<template>
<div>
<h3>{{$store.state.count}}------{{count}}</h3>
<h3>{{$store.state.count}}------{{a}}</h3>
<hr/>
<p>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
data(){
return{
msg:"hello vuex"
}
},
computed: mapState({
count:state=>state.count
}),
store
}
</script>
<style>
</style>
- 通过computed+mapState的数组来使用
<template>
<div>
<h3>{{$store.state.count}}------{{count}}</h3>
<h3>{{$store.state.count}}------{{a}}</h3>
<hr/>
<p>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
data(){
return{
msg:"hello vuex"
}
},
//名称要与state中的数据属性名称相同
computed:{...mapState(['count'])},
store
}
</script>
<style>
</style>
|你知道的越多,不知道的越多。 |如果本文章内容有问题,请直接评论或者私信我。如果觉得写的还不错的话,点个赞也是对我的支持哦。 |未经允许,不得转载!|微信搜【程序员徐小白】,关注即可第一时间阅读最新文章。回复【面试题】有我准备的50道高频校招面试题,以及各种学习资料。

浙公网安备 33010602011771号