【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?
生活随笔
收集整理的這篇文章主要介紹了
【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是Vuex?只需三分鐘!只需創建一個vuex.js文件,讓你馬上學會使用Vuex,盡管Vuex是個雞肋!(扔掉store文件夾和里面的index、getters、actions、mutations等js文件吧!)_你摯愛的強哥?給你發來1條消息?-CSDN博客https://s-z-q.blog.csdn.net/article/details/119792336
ng g s storage
storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({providedIn: 'root'
})
export class StorageService {text = '初始值';color = 'gray';
}
app.component.html、app.component.css、app.component.ts
<button (click)="storageService.text='全局改變后的值';storageService.color='red'">改變全局變量(文字變紅色)</button>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>
<app-other></app-other>________________________________________________________________________________[color="gray"] {color: gray;
}
[color="red"] {color: red;
}________________________________________________________________________________import { Component } from '@angular/core';
import { StorageService } from './services/storage.service';
@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {constructor(public storageService: StorageService,) {}
}
components/other.component.html、components/other.component.css、components/other.component.ts?
<p>其他組件:</p>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>________________________________________________________________________________[color="gray"] {color: gray;
}
[color="red"] {color: red;
}________________________________________________________________________________import { Component } from '@angular/core';
import { StorageService } from '../../services/storage.service';
@Component({selector: 'app-other',templateUrl: './other.component.html',styleUrls: ['./other.component.css']
})
export class OtherComponent {constructor(public storageService: StorageService,) {}
}
點擊按鈕后
總結
以上是生活随笔為你收集整理的【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【fiveKeyPress】2秒内五次点
- 下一篇: 设置VSCode Git签出分支快捷键A