zmb*_*mbq 8 typescript vue.js vuex
我正在努力让Vuex商店成为非常友好的.我按照这里的解释建造商店.但是,当我this.$store从组件访问时,类型是Store<any>.
我无法弄清楚如何更改它,以便默认为Store<MyState>每次都不需要演员.
不幸的是,不可能用Store<any>更具体的类型覆盖 VueX 类型定义的类型。我能想到的最好办法是添加第二个返回$store但类型正确的字段,这样您就不必在任何地方使用强制转换或在所有组件中声明它:
import { Store } from "vuex";
// Type the $tstore properly, which is the same as $store but properly typed.
// Unfortunately you cannot override the Store<any> type.
declare module "vue/types/vue" {
interface Vue {
$tstore: Store<State>;
}
}
// Set $tstore to be a getter that simply returns $store.
Object.defineProperty(Vue.prototype, "$tstore", {
get: function() {
return this.$store as Store<State>;
},
enumerable: true,
});
Run Code Online (Sandbox Code Playgroud)
小智 5
如果有人遇到这个 - 我们通过重新定义构造函数返回的类型来解决这个问题 -
import Vue, { VueConstructor } from 'vue'
import { Store } from 'vuex'
import { RootState } from '@/store/types'
abstract class VueStrongClass extends Vue {
public $store!: Store<RootState>
}
const VueStrong = Vue as VueConstructor<VueStrongClass>;
export default VueStrong;
Run Code Online (Sandbox Code Playgroud)
然后我们就
export default VueStrong.extend({
name: 'name',
components: {
componentA,
componentB,
},
Run Code Online (Sandbox Code Playgroud)
这让我们可以正确使用打字:
methods: {
sessionStarted(): Boolean | undefined {
return this.$store.state.sessionState?.session.started;
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
369 次 |
| 最近记录: |