您的位置:首页 > 产品设计 > UI/UE

Vuex的State学习

2018-02-24 20:35 169 查看

Vuex 的 State 学习

  Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。

  目录:

Vuex 的 State 学习
例子

将 store 注入到每个子组件

mapState 辅助函数

对象展开运算符实现与局部计算属性使用

例子

  新建一个 store.js 文件用于创建 store 实例:

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
state: {
count: 0
}
})

export default store


在组件 App.vue 中获取 Vuex 状态:

// App.vue
<template>
<!-- ... -->
</template>

<script>
import store from "./store.js";  // 导入 store 实例

export default {
data() {
return {}
},
created:function(){
console.log(store.state.count); // 0
console.log(this.count);    // 0
},
computed:{
count(){
// 在计算属性中返回某个状态
return store.state.count;
}
}
}
</script>


将 store 注入到每个子组件

  Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):

// main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store.js'

Vue.use(Vuex);      // 调用Vue.use(Vuex)

new Vue({
el: '#app',
store,    // “注入”
render: h => h(App)
})


  再在 App.vue 中获取 Vuex 状态:

// App.vue
<template>
<!-- ... -->
</template>

<script>
// import store from "./store.js";  // 现在可以不用在每个 vue 组件中导入 store 实例了

export default {
data() {
return {}
},
created:function(){
console.log(this.count);   // 0
},
computed:{
count(){
return this.$store.state.count;
}
}
}
</script>


mapState 辅助函数

  当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
state: {
count: 0,
foo: 'foo',
bar: 'bar'
}
})

export default store


// App.vue

<template>
<!-- ... -->
</template>

<script>
import store from "./store.js";

export default {
data() {
return {
local: "(and local)"
}
},
created:function(){
console.log(this.count);    // 0
console.log(this.foo);      // foo
console.log(this.bar);      // bar(and local)
},
computed:mapState({
// 箭头函数可使代码更简练
count: state => state.count,

// 传字符串参数 'foo' 等同于 `sate => state.foo`
foo: 'foo',

// 为了能够使用 `this` 获取局部状态,必须使用常规函数
bar (state) {
return state.bar + this.local;
},
}),
methods: {
add(){
store.commit('increment');
}
}
}
</script>


使用 mapState 辅助函数的时候也可以传入一个数组:

created:function(){
console.log(this.count);  // 0
console.log(this.foo);       // foo
console.log(this.bar);      // bar(and local)
},
// 传一个数组
computed: mapState([
//映射 this.count 为 store.state.count
'count',
'foo',
'bar'
])


对象展开运算符实现与局部计算属性使用

  实际上,我们除了从 store 中获取状态作为计算属性来使用之外,我们还有自己本身所需要的一些计算属性,所以在使用 mapState 辅助函数的时候,我们还需要使用对象展开运算符来实现与局部计算属性结合。

computed: {
localComputed () {
return `local computed`
},
...mapState({
count: state => state.count
})
}


  还可以传入一个数组:

computed: {
localComputed () {
return `local computed`
},
// 使用对象展开运算符将此对象混入到外部对象中,可以传一个数组或一个对象
// ...mapState({
//     count: state => state.count
// })
...mapState([
'count'
])
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue vuex state