虽然 父组件 方法(通过属性传递数据)是一个完美的有效且良好的实现,我们可以使用 store 以更简单的方式实现同样的事情 工厂。
基本上,数据由 Store 保存,在两个组件范围内都引用它,从而在状态更改时启用 UI 的响应式更新。
例子:
angular
.module('YourApp')
// declare the "Store" or whatever name that make sense
// for you to call it (Model, State, etc.)
.factory('Store', () => {
// hold a local copy of the state, setting its defaults
const state = {
data: {
heroes: [],
viewType: 'grid'
}
};
// expose basic getter and setter methods
return {
get() {
return state.data;
},
set(data) {
Object.assign(state.data, data);
},
};
});
然后,在您的组件中,您应该有如下内容:
angular
.module('YourApp')
.component('headerComponent', {
// inject the Store dependency
controller(Store) {
// get the store reference and bind it to the scope:
// now, every change made to the store data will
// automatically update your component UI
this.state = Store.get();
// ... your code
},
template: `
<div ng-show="$ctrl.state.viewType === 'grid'">...</div>
<div ng-show="$ctrl.state.viewType === 'row'">...</div>
...
`
})
.component('mainComponent', {
// same here, we need to inject the Store
controller(Store) {
// callback for the switch view button
this.switchViewType = (type) => {
// change the Store data:
// no need to notify or anything
Store.set({ viewType: type });
};
// ... your code
},
template: `
<button ng-click="$ctrl.switchViewType('grid')">Switch to grid</button>
<button ng-click="$ctrl.switchViewType('row')">Switch to row</button>
...
`
如果您想查看一个工作示例,check out this CodePen。
这样做您还可以启用 2 或 N 个组件之间的通信。你只需要:
- 注入存储依赖
- 确保将商店数据链接到组件范围
就像上面的例子一样 (<header-component>)。
在现实世界中,典型的应用程序需要管理大量数据,因此以某种方式在逻辑上拆分数据域更有意义。遵循相同的方法您可以添加更多 Store 工厂。例如,要管理当前记录的用户信息和外部资源(即目录),您可以构建一个UserStore 加上一个CatalogStore——或者UserModel 和CatalogModel; 这些实体也是集中处理与后端通信、添加自定义业务逻辑等事情的好地方。数据管理将由Store 工厂单独负责。
请注意,我们正在改变商店数据。虽然这种方法非常简单明了,但它可能无法很好地扩展,因为会产生side effects。如果您想要更高级的东西(不变性、纯函数、单状态树等),请查看 Redux,或者如果您最终想切换到 Angular 2,请查看 ngrx/store。
希望这会有所帮助! :)
您不必使用 Angular 2 方式,因为以防万一
你有时会迁移......如果你觉得这样做是有意义的,那就去做吧。