主要可以分为四个部分「state」、「getters」、「mutation」、「actions」,接着我们就一一的了解他们的功能吧!
就是昨天说的仓库!!
首先,把需要共用的资料放入state中
// src/store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
greeting: 'hello vuex'
}
})
再来修改App.vue,用computed方式向仓库取得资料
<template>
<h1>{{ greeting }}</h1>
</template>
<script>
export default {
name: "App",
computed: {
greeting() {
return this.$store.state.greeting;
},
},
};
</script>
共用的资料在未来可能会愈来多,一笔笔使用computed
取得变得很麻烦,透过mapState
可以一次引入多笔。
// src/store/index.js
state: {
greeting: 'hello vuex',
year: 2021,
month: 'Oct'
},
用mapState
传入阵列,使用之前要先import
进来
import { mapState } from "vuex";
export default {
name: "App",
computed: mapState(["greeting", "year", "month"]),
};
但是这样的写法会将整个元件的computed
吃掉,若要增加其他属性就必须用解构语法,才可以同时保有mapState
和元件本身的computed
属性。
import { mapState } from "vuex";
export default {
name: "App",
computed: {
...mapState(["greeting", "year", "month"]),
name(){
return '$(this.name) is awesome'
}
}
};
除了使用阵列之外,也可以使用物件指定元件立面的key
computed: {
...mapState({
greetingWord:"greeting"
}),
}
//or 函式形式
computed: {
...mapState({
greetingWord:state => state.greeting
}),
}
getters的角色就像是store中的computed
书中范例 :
state: {
product: 't-shirt',
price: 500,
quantity: 100
},
想针对这个商品做促销,从state中取得资料後再自己使用computed计算
computed: {
...mapState(["product", "price", "quantity"]),
sellingPrice() {
//八折优惠
return this.price * 0.8;
},
},
可是这个促销价会出现在网页其他的元件内,若每个元件都要写一次打八折很有可能出现不一致的错误,为了「单一资料来源」原则,我们应该先做计算,元件直接取计算後的值比较好,getters就在此出场拉!
// src/store/index.js
state: {
product: 't-shirt',
price: 500,
quantity: 100
},
getters: {
sellingPrice(state) {
//八折优惠
return state.price * 0.8;
},
},
//App.vue
computed: {
...mapState(["product", "price", "quantity"]),
sellingPrice() {
//八折优惠
return this.$store.getters.sellingPrice;
},
},
另外,getters除了有取得state资料的功能外,他也可以取其他getters的资讯。接续范例,商品售价依照库存决定,库存少於50打八折,否则打九折。
state: {
product: 't-shirt',
price: 500,
quantity: 100
},
getters: {
discount(state) {
return (state.quantity > 50) ? 0.8 : 0.9
},
sellingPrice(state, getters) {
return state.price * getters.discount
},
},
概念和用法和mapState一样(要记得import)
computed: {
...mapState([
product: 't-shirt',
price: 500,
quantity: 100
]),
...mapGetters([
'sellingPrice'
]),
}
今天时间有点来不及,剩下的部分明天继续!!!!
Spinner下拉式选单 这也很常用在表单中 如:选择地区、居住地、选择语言、学校 那今天就来学习点...
今天首要进行的就是调整瞄准到攻击的过程。 怪物呈现调整 怪物调整过面向後,为了要让部份UI做为正面提...
今天继续来谈阵列中的方法,今天主要将重点聚焦在如何往阵列新增或移除元素,同样的废话不多说,咱们直接进...
接续上篇继续提到关於有限公司以及股份有限公司的差别。 有限公司以及股份有限公司除了制度会有差别外,责...
Azure cognitive service: Translator- 让 Azure 帮你翻译 ...