d-_*_*_-b 7 javascript mixins vue.js
我有一个 Vue.js 应用程序,它加载一个项目列表,每个项目都作为 a 传递prop给一个 Vue 组件。
我想通了,通过使用mixins我可以共享共同的部件属性,如computed,created等
现在,我正在尝试对项目列表进行排序,但无法弄清楚如何访问每个组件的计算属性以应用排序/过滤。我怎样才能做到这一点?
项目
[{
price: 10,
qty: 2
}, {
price: 8,
qty: 3
}]
Run Code Online (Sandbox Code Playgroud)
Mixin - ./Cost.js
export default {
computed: {
cost () {
return this.price * this.qty;
}
}
}
Run Code Online (Sandbox Code Playgroud)
组件(按预期工作) - ./Product.vue
import Cost from './Cost.js'
export default {
name: 'product-item',
props: ['product'],
mixins: [Cost]
}
Run Code Online (Sandbox Code Playgroud)
您将如何访问计算属性或重构此设置?
列表组件
<template>
<div id="list">
<div v-for="product in sorted" :product="product">Cost: {{ cost }} </div>
</div>
</template>
<script>
import ProductItem from './Product.vue'
export default {
components: { ProductItem },
created: () {
this.items = [...] // as noted above
},
computed: {
sorted () {
return this.items.sort( (a,b) => b.cost - a.cost); // cost is not accessible!
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
使用vuex. 您vuex store将提供一个getters可以包装到多个组件的本机computed对象中或直接访问的对象。您的代码将是 DRY、反应式、缓存和可维护的。
根据我的经验,一旦您需要超越child-parent数据关系,vuex, store, 和shared state就是要走的路。一旦你掌握了它,你的应用程序的发展方式就非常神奇了。
展示如何安装vuex. 访问https://vuex.vuejs.org/guide/getters.html以了解 getter 与计算属性的相似之处,以及在组件之间共享的价值。官方 Vuex 指南还将演示如何使用商店初始化您的 Vue 实例。
下面是一些片段向您展示演员的vuex系统。
// state definition (basically a shared reactive 'data' object that lives outside components)
state:{
message:'Hello'
}
// the store getters are declared as methods and accessed as properties (just like component/computed)
getters:{
message: state => return state.message
}
Run Code Online (Sandbox Code Playgroud)
// component 1 wraps getter
computed:{
message(){
return this.$store.getters.message
}
}
// component 2 also wraps getter
computed:{
message(){
return this.$store.getters.message
}
}
Run Code Online (Sandbox Code Playgroud)
// state definition (basically a shared reactive 'data' object that lives outside components)
state:{
message:'Hello'
}
// the store getters are declared as methods and accessed as properties (just like component/computed)
getters:{
message: state => return state.message
}
Run Code Online (Sandbox Code Playgroud)
一旦你开始使用vuex,各种其他的宝物就会开始出现,比如 Chrome 中的开发者工具、撤消/重做支持、状态的简单重构、时间旅行调试、应用程序持久化等。 还有添加多个商店的快捷方式getter 进入你的计算属性。
| 归档时间: |
|
| 查看次数: |
3501 次 |
| 最近记录: |