vue#computed TypeScript Examples
The following examples show how to use
vue#computed.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From hexon with GNU General Public License v3.0 | 8 votes |
export function useAsyncComponentWithLoading(
loader: Parameters<typeof defineAsyncComponent>[0]
): [ReturnType<typeof defineAsyncComponent>, ComputedRef<boolean>] {
const loading = ref(true)
const _loader = "loader" in loader ? loader.loader : loader
return [
defineAsyncComponent(() =>
_loader().then((res) => {
loading.value = false
return res
})
),
computed(() => loading.value),
]
}
Example #2
Source File: utils.ts From awakened-poe-trade with MIT License | 7 votes |
export function configModelValue<ObjectT extends object, KeyT extends keyof ObjectT> (
getObj: () => ObjectT,
key: KeyT
) {
return computed<ObjectT[KeyT]>({
get () {
return getObj()[key]
},
set (value) {
getObj()[key] = value
}
})
}
Example #3
Source File: index.ts From hexon with GNU General Public License v3.0 | 6 votes |
export function createLoadingPlugin(): Loading {
let token: NodeJS.Timeout | undefined
const loading = ref(false)
return {
loading: computed(() => loading.value),
start() {
token = setTimeout(() => {
loading.value = true
}, 500)
},
stop() {
if (token) {
clearTimeout(token)
token = undefined
}
loading.value = false
},
install(app: App) {
const loading = this
app.provide(key, loading)
},
}
}
Example #4
Source File: store.ts From vue3-treeview with MIT License | 6 votes |
export function createState(props: ITreeProps): string {
const { nodes, config } = toRefs(props);
const state: IState = {
id: uniqueId(),
nodes: computed(() => nodes.value),
config: computed(() => config.value),
focusable: ref(null),
focusFunc: new Map<string, Function>(),
dragged: ref({
node: null,
element: null,
wrapper: null,
parentId: null
}),
};
states.set(state.id, state);
return state.id;
}
Example #5
Source File: Leagues.ts From awakened-poe-trade with MIT License | 6 votes |
selected = computed<string | undefined>({
get () {
return (tradeLeagues.value.length)
? AppConfig().leagueId
: undefined
},
set (id) {
AppConfig().leagueId = id
}
})
Example #6
Source File: inject.ts From fect with MIT License | 6 votes |
useProvider = <T>(key: InjectionKey<Provider<T>>) => {
const context = inject(key, null)
if (context) {
const instance = getCurrentInstance()!
const { link, unlink, internalChildren, ...rest } = context
link(instance)
onUnmounted(() => unlink(instance))
const idx = computed(() => internalChildren.indexOf(instance))
return {
context: rest,
idx: idx.value
}
}
return {
context: null,
idx: -1
}
}
Example #7
Source File: lib.ts From hexon with GNU General Public License v3.0 | 6 votes |
export function useTheme<N extends Exclude<keyof IGlobalTheme, "common">>(
id: N
) {
const { globalThemeRef } = inject(key)!
const themeRef = computed(() => {
const { common } = globalThemeRef.value
return merge(
{},
common,
globalThemeRef.value[id]?.self(common) as ReturnType<
IGlobalTheme[N]["self"]
>
)
})
return themeRef
}
Example #8
Source File: Store.ts From universal-model-vue with MIT License | 6 votes |
constructor(initialState: T, selectors?: Selectors<T, U>) {
this.reactiveState = reactive(initialState);
this.reactiveSelectors = {} as ComputedSelectors<T, U>;
if (selectors) {
Object.keys(selectors).forEach(
(key: keyof U) =>
(this.reactiveSelectors[key] = computed(() =>
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
selectors[key](this.reactiveState)
))
);
}
}
Example #9
Source File: create-classnames.ts From hexon with GNU General Public License v3.0 | 6 votes |
/**
* @param prefix prefix
* @param fn config function
* @returns
*/
export function createClassNames(
prefix: string,
fn: (
add: (name: string) => void,
m: (...names: string[]) => string
) => void = () => {}
) {
const classNames = computed(() => {
const classNames: any[] = [prefix]
/**
* add a classname
* @param name classname
*/
function add(name: string) {
classNames.push(name)
}
/**
* create a classname with a modification name `prefix-mod1-mod2-*-modn`
* @param names modification name
* @returns
*/
function m(...names: string[]) {
return `${prefix}-${names.join("-")}`
}
fn(add, m)
return classNames
})
return { classNames, prefix }
}
Example #10
Source File: common.ts From vue3-ts-base with MIT License | 6 votes |
canEditTeam = computed(() => {
if (store.state.user.userDetail.type === 0) {
return true
}
const canEditTeamRoleList = [
RoleType['超级管理员'],
RoleType['团队超级管理员'],
RoleType['团队管理员']
]
if (
canEditTeamRoleList.includes(store.state.user.currentTeamRoleId as number)
) {
return true
}
return false
})
Example #11
Source File: useParam.ts From jz-gantt with MIT License | 6 votes |
useParamObject = () => {
const store = useStore();
const { GtParam } = store;
return {
GtParam,
oneDayWidth: computed(() => {
const size = GtParam.ganttOptions.columnSize ?? 'normal';
switch (size) {
case 'small':
if (GtParam.headerUnit === 'week') return 7;
if (GtParam.headerUnit === 'month') return 4;
return 15;
case 'large':
if (GtParam.headerUnit === 'week') return 30;
if (GtParam.headerUnit === 'month') return 15;
return 60;
case 'normal':
default:
if (GtParam.headerUnit === 'week') return 15;
if (GtParam.headerUnit === 'month') return 8;
return 30;
}
})
};
}
Example #12
Source File: scope-element.ts From quantum-sheet with GNU General Public License v3.0 | 6 votes |
/*const imports = computed(() => {
variables.forEach((value, key) => {
if(value[0].getters.length > 0) {
.push()
}
});
})*/
private createVariableArray(name: string): ScopedVariable[] {
// First variable, used to import values from the scope above
const importerVariable: ScopedVariable = reactive({
position: computed(() => this.position.value),
index: 0,
data: shallowRef(),
getters: [],
})
const newVariableArray = reactive([importerVariable])
// Cleanup if unused
watch([() => newVariableArray.length, () => importerVariable.getters.length], ([variableArrayLength, gettersLength]) => {
if (variableArrayLength <= 1 && gettersLength == 0) {
this._variableMap.delete(name)
}
})
this._variableMap.set(name, newVariableArray)
return newVariableArray
}
Example #13
Source File: use-breakpoint.ts From vooks with MIT License | 6 votes |
function useBreakpoint<T extends BreakpointOptions = DefaultBreakpointOptions> (
screens?: T
): ComputedRef<ExtractBreakpoint<T> | undefined> {
if (!isBrowser) return computed(() => undefined)
// pass ts check
const breakpointsRef =
screens !== undefined ? useBreakpoints(screens) : useBreakpoints()
return computed(() => {
const { value } = breakpointsRef
if (value.length === 0) return undefined
return value[value.length - 1] as any
})
}
Example #14
Source File: productsApi.ts From master-frontend-lemoncode with MIT License | 6 votes |
useProductsApi = async (): Promise<{
list: Ref<Product[]>
totalProducts: ComputedRef<number>
}> => {
const list: Ref<Product[]> = ref([])
list.value = await productService.get()
const totalProducts = computed(() => {
return list.value.length
})
return { list, totalProducts }
}
Example #15
Source File: LoginControl.ts From LiveAtlas with Apache License 2.0 | 6 votes |
private async handleClick() {
const logoutSuccess = computed(() => this.store.state.messages.logoutSuccess),
logoutError = computed(() => this.store.state.messages.logoutErrorUnknown);
if (this.loggedIn.value) {
try {
await this.store.dispatch(ActionTypes.LOGOUT, undefined);
notify(logoutSuccess.value);
} catch(e) {
notify(logoutError.value);
}
} else {
this.store.commit(MutationTypes.SHOW_UI_MODAL, 'login');
}
}
Example #16
Source File: use-merged-state.ts From vooks with MIT License | 6 votes |
export default function useMergedState<T> (
controlledStateRef: Ref<T | undefined>,
uncontrolledStateRef: Ref<T>
): ComputedRef<T> {
watch(controlledStateRef, value => {
if (value !== undefined) {
uncontrolledStateRef.value = value
}
})
return computed(() => {
if (controlledStateRef.value === undefined) {
return uncontrolledStateRef.value
}
return controlledStateRef.value
})
}
Example #17
Source File: useParent.ts From elenext with MIT License | 6 votes |
useParent = <T>(key: InjectionKey<ParentProvide<T>>) => {
const instance = getCurrentInstance() as ComponentInternalInstance
const parent = inject(key, null)
const index = computed(() => parent?.children.indexOf(instance))
parent?.insert(instance)
onUnmounted(() => {
parent?.remove(instance)
})
return { parent, index }
}
Example #18
Source File: use-compitable.ts From vooks with MIT License | 6 votes |
export default function useCompitable<T extends object, U extends Array<keyof T>, V extends keyof T> (
reactive: T,
keys: [...U, V]
): ComputedRef<T[V]> {
// @ts-expect-error
return computed(() => {
for (const key of keys) {
if (reactive[key] !== undefined) return reactive[key]
}
return reactive[keys[keys.length - 1]]
})
}
Example #19
Source File: document-storage.ts From quantum-sheet with GNU General Public License v3.0 | 5 votes |
export function useDocumentStorage() {
/** Adds a file-handle to the storage and returns its ID */
async function addFile(file: FileWithHandle): Promise<string> {
await initPromise
// Deduplicate file handles
if (file.handle) {
for (const existingFile of files.values()) {
if (existingFile.fileHandle.handle && file.handle.isSameEntry(existingFile.fileHandle.handle)) {
return existingFile.id
}
}
}
const id = uuidv4()
const databaseFile: DatabaseFile = {
id,
fileHandle: file,
}
files.set(id, databaseFile)
await set('documents', toRaw(files))
return id
}
async function removeFile(id: string) {
if (files.delete(id)) {
await set('documents', toRaw(files))
}
}
/** Gets the actual content of a file */
async function getFileContent(id: string): Promise<string | undefined> {
await initPromise
const databaseFile = files.get(id)
if (!databaseFile) return
const fileContent = await databaseFile.fileHandle.text()
return fileContent
}
/** Saves a file back to the harddisk */
async function saveFile(opts: { id?: string; name?: string; content: string }) {
const databaseFile = opts.id ? files.get(opts.id) : undefined
const name = opts.name ?? databaseFile?.fileHandle.name ?? 'document'
const hasExtension = /\.qd/.test(name)
await fileSave(
new Blob([opts.content], {
type: 'text/plain',
}),
{
fileName: hasExtension ? name : name + '.qd',
extensions: ['.qd'],
},
databaseFile?.fileHandle?.handle
)
}
return {
isLoaded,
addFile,
removeFile,
getFileContent,
saveFile,
files: computed(() =>
Array.from(files.values()).map((v) => {
return {
id: v.id,
name: v.fileHandle.name,
}
})
),
}
}
Example #20
Source File: index.ts From vue3-gettext with MIT License | 5 votes |
export function createGettext(options: Partial<GetTextOptions> = {}) {
Object.keys(options).forEach((key) => {
if (Object.keys(defaultOptions).indexOf(key) === -1) {
throw new Error(`${key} is an invalid option for the translate plugin.`);
}
});
const mergedOptions = {
...defaultOptions,
...options,
};
const translations = ref(normalizeTranslations(mergedOptions.translations));
const gettext: Language = reactive({
available: mergedOptions.availableLanguages,
muted: mergedOptions.mutedLanguages,
silent: mergedOptions.silent,
translations: computed({
get: () => {
return translations.value;
},
set: (val: GetTextOptions["translations"]) => {
translations.value = normalizeTranslations(val);
},
}),
current: mergedOptions.defaultLanguage,
install(app: App) {
// TODO: is this needed?
(app as any)[GetTextSymbol] = gettext;
app.provide(GetTextSymbol, gettext);
if (mergedOptions.setGlobalProperties) {
const globalProperties = app.config.globalProperties;
globalProperties.$gettext = gettext.$gettext;
globalProperties.$pgettext = gettext.$pgettext;
globalProperties.$ngettext = gettext.$ngettext;
globalProperties.$npgettext = gettext.$npgettext;
globalProperties.$gettextInterpolate = gettext.interpolate;
globalProperties.$language = gettext;
}
if (mergedOptions.provideDirective) {
app.directive("translate", Directive(gettext));
}
if (mergedOptions.provideComponent) {
// eslint-disable-next-line vue/multi-word-component-names, vue/component-definition-name-casing
app.component("translate", Component);
}
},
}) as unknown as Language;
const translate = translateRaw(gettext);
const interpolate = interpolateRaw(gettext);
gettext.$gettext = translate.gettext.bind(translate);
gettext.$pgettext = translate.pgettext.bind(translate);
gettext.$ngettext = translate.ngettext.bind(translate);
gettext.$npgettext = translate.npgettext.bind(translate);
gettext.interpolate = interpolate.bind(interpolate);
gettext.directive = Directive(gettext);
gettext.component = Component;
return gettext;
}
Example #21
Source File: expression-element.ts From quantum-sheet with GNU General Public License v3.0 | 5 votes |
private readonly blockPosition = computed(() => this.position.value)
Example #22
Source File: component.ts From vue3-gettext with MIT License | 5 votes |
Component = defineComponent({
// eslint-disable-next-line vue/multi-word-component-names, vue/component-definition-name-casing
name: "translate",
props: {
tag: {
type: String,
default: "span",
},
// Always use v-bind for dynamically binding the `translateN` prop to data on the parent,
// i.e.: `:translate-n`.
translateN: {
type: Number,
default: null,
},
translatePlural: {
type: String,
default: null,
},
translateContext: {
type: String,
default: null,
},
translateParams: {
type: Object,
default: null,
},
translateComment: {
type: String,
default: null,
},
},
setup(props, context) {
const isPlural = props.translateN !== undefined && props.translatePlural !== undefined;
if (!isPlural && (props.translateN || props.translatePlural)) {
throw new Error(
`\`translate-n\` and \`translate-plural\` attributes must be used together: ${
context.slots.default?.()[0]?.children
}.`,
);
}
const root = ref<HTMLElement>();
const plugin = useGettext();
const msgid = ref<string | null>(null);
onMounted(() => {
if (!msgid.value && root.value) {
msgid.value = root.value.innerHTML.trim();
}
});
const translation = computed(() => {
const translatedMsg = translate(plugin).getTranslation(
msgid.value!,
props.translateN,
props.translateContext,
isPlural ? props.translatePlural : null,
plugin.current,
);
return interpolate(plugin)(translatedMsg, props.translateParams, undefined, getCurrentInstance()?.parent);
});
// The text must be wraped inside a root HTML element, so we use a <span> by default.
return () => {
if (!msgid.value) {
return h(props.tag, { ref: root }, context.slots.default ? context.slots.default() : "");
}
return h(props.tag, { ref: root, innerHTML: translation.value });
};
},
})
Example #23
Source File: useResize.ts From jz-gantt with MIT License | 5 votes |
/**
* 悬停按钮的定位方法
*/
export function useBtnPosition() {
const size = ref(30);
const top = ref(size.value * 2);
const right = ref(-size.value / 2);
const opBtnStyle = computed(() => {
return {
position: ' absolute',
right: `${right.value}px`,
top: `${top.value}px`,
zIndex: 99
};
});
const originPosition = ref<null | number>(null);
function onOpBtnMouseLeave() {
if (isNumber(originPosition.value)) {
right.value = originPosition.value;
}
}
function onOpBtnMouseEnter() {
if (right.value >= 0) {
originPosition.value = null;
return;
}
originPosition.value = right.value;
right.value = 0;
}
return {
btnSize: readonly(size),
opBtnStyle,
onOpBtnMouseLeave,
onOpBtnMouseEnter
};
}
Example #24
Source File: scope-element.ts From quantum-sheet with GNU General Public License v3.0 | 5 votes |
addGetter(name: string, position: ComputedRef<Vector2>): UseScopedGetter {
const getter: ScopedGetter = reactive({
position: position,
variable: undefined,
})
const data = computed(() => getter.variable?.data)
const variableArray = this.variableMap.get(name) ?? this.createVariableArray(name)
watchImmediate(
() => getter.position,
(value) => {
if (getter.variable) {
// If the getter is still in the correct position, bail out
const nextVariable = arrayUtils.at(variableArray, getter.variable.index + 1)
if (
isInRange(value, {
start: getter.variable.position,
end: nextVariable?.position,
})
) {
return
}
// Remove getter from old variable
arrayUtils.remove(getter.variable.getters, getter)
getter.variable = undefined
}
const { index } = arrayUtils.getBinaryInsertIndex(variableArray, (v) => v.position.compareTo(value))
const variable = arrayUtils.at(variableArray, index - 1)
assert(variable, `Getter position ${getter.position} outside of block ${this.position}`)
// Add getter to variable
variable.getters.push(getter)
getter.variable = variable
}
)
function remove() {
if (!getter.variable) return
arrayUtils.remove(getter.variable.getters, getter)
getter.variable = undefined
}
return {
data,
remove,
}
}
Example #25
Source File: useDate.ts From jz-gantt with MIT License | 5 votes |
export function useWeekend() {
const { GtData } = useData();
const { GtParam, oneDayWidth } = useParam();
const { ganttWidth } = useResize();
const { colorSelectStr } = useDark();
const weekendList = computed(() => {
const r: Array<number> = [];
if (!GtParam.ganttOptions.showWeekend || GtParam.headerUnit !== 'day')
return r;
const sd = createDate(GtData.start);
let d = sd.getDay();
let i = 0;
// start is Sunday
if (d === 0) {
r.push(d);
d += 6;
i += 6;
}
// start is work day
while (d > 0 && d < 6) {
d++;
i++;
}
// Cycle to find Saturday and Sunday
while (i * oneDayWidth.value < ganttWidth.value) {
r.push(i);
r.push(++i);
++d;
d += 6;
i += 6;
}
return r;
});
const weekendStyle = computed(() => {
return (item: number) => {
return {
left: `${item * oneDayWidth.value}px`,
width: `${oneDayWidth.value}px`,
height: '100%',
'background-color':
GtParam.ganttOptions.body?.weekendColor ||
Variables.color.weekend[colorSelectStr.value]
};
};
});
return {
weekendList,
weekendStyle
};
}
Example #26
Source File: nav-config.ts From hexon with GNU General Public License v3.0 | 5 votes |
export function useNavConfig() {
const vars = useThemeVars()
const config = [
{
type: "item" as const,
text: "用户",
icon: HIconName.Contact,
color: vars.value.colorSuccess,
key: "user" as const,
comp: markRaw(UserView),
},
{
type: "item" as const,
text: "安全",
icon: HIconName.ReportHacked,
color: vars.value.colorPrimary,
key: "security" as const,
comp: markRaw(SecurityView),
},
{
type: "item" as const,
text: "样式",
icon: HIconName.OEM,
color: vars.value.colorWarning,
key: "style" as const,
comp: markRaw(StyleView),
},
{
type: "item" as const,
text: "关于",
icon: HIconName.Info,
color: vars.value.textColorSecondary,
key: "about" as const,
comp: markRaw(AboutView),
},
{
type: "item" as const,
text: "帮助",
icon: HIconName.EaseOfAccess,
color: vars.value.textColorSecondary,
key: "help" as const,
comp: markRaw(HelpView),
},
]
const fullConfig = computed(() => {
return config.map((value, idx) => ({ idx, ...value }))
})
function getConfig(key: typeof fullConfig.value[number]["key"]) {
return fullConfig.value.find((item) => item.key === key)!
}
return { config: fullConfig, getConfig }
}
Example #27
Source File: use-breakpoints.ts From vooks with MIT License | 5 votes |
function useBreakpoints<T extends BreakpointOptions> (
screens: T = defaultBreakpointOptions as unknown as T
): ComputedRef<Array<ExtractBreakpoint<T>>> {
if (!isBrowser) return computed(() => [])
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (typeof window.matchMedia !== 'function') return computed(() => [])
type BreakpointStatus = ExtractBreakpointStatus<T>
const breakpointStatusRef = ref<BreakpointStatus>({} as BreakpointStatus)
const breakpoints = Object.keys(screens)
const updateBreakpoints: OnMqlChange = (e, breakpointName) => {
if (e.matches) breakpointStatusRef.value[breakpointName] = true
else breakpointStatusRef.value[breakpointName] = false
}
breakpoints.forEach((key) => {
const breakpointValue = screens[key]
let mql: MediaQueryList
let cbs: Set<OnMqlChange>
if (mqlMap[breakpointValue] === undefined) {
mql = window.matchMedia(createMediaQuery(breakpointValue))
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (mql.addEventListener) {
mql.addEventListener('change', (e: MediaQueryListEvent) => {
cbs.forEach((cb) => {
cb(e, key)
})
})
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
} else if (mql.addListener) {
mql.addListener((e: MediaQueryListEvent) => {
cbs.forEach((cb) => {
cb(e, key)
})
})
}
cbs = new Set()
mqlMap[breakpointValue] = {
mql,
cbs
}
} else {
mql = mqlMap[breakpointValue].mql
cbs = mqlMap[breakpointValue].cbs
}
cbs.add(updateBreakpoints)
if (mql.matches) {
cbs.forEach((cb) => {
cb(mql, key)
})
}
})
onBeforeUnmount(() => {
breakpoints.forEach((breakpoint) => {
const { cbs } = mqlMap[screens[breakpoint]]
if (cbs.has(updateBreakpoints)) {
cbs.delete(updateBreakpoints)
}
})
})
return computed<Array<ExtractBreakpoint<T>>>(() => {
const { value } = breakpointStatusRef
return breakpoints.filter((key) => value[key]) as any
})
}
Example #28
Source File: theme.ts From hexon with GNU General Public License v3.0 | 5 votes |
export function useMonacoTheme() {
const vars = useThemeVars()
const custom = computed(() => {
return {
base: (vars.value.isDark
? "vs-dark"
: "vs") as monaco.editor.BuiltinTheme,
inherit: true,
rules: [
{
foreground: removeHash(vars.value.textColorSecondary),
token: "comment.content.md",
},
{
foreground: removeHash(vars.value.textColorSecondary),
token: "comment.md",
},
{
foreground: removeHash(vars.value.textColorPrimary),
token: "string.md",
},
{
// 链接
foreground: removeHash(vars.value.colorPrimary),
token: "string.link.md",
fontStyle: "blod",
},
{
// 标题
foreground: removeHash(vars.value.colorPrimary),
token: "keyword.md",
},
{
// 标题
foreground: removeHash(vars.value.colorPrimary),
token: "keyword",
},
{
foreground: removeHash(vars.value.colorPrimary),
fontStyle: "bold",
token: "variable.md",
},
],
colors: {
"editor.foreground": vars.value.textColorPrimary,
"editor.background": vars.value.backgroundColorPrimary,
"editorCursor.foreground": vars.value.colorPrimary,
"editor.selectionBackground": vars.value.isDark
? "#ffffff35"
: "#00000015",
},
}
})
const update = () => {
monaco.editor.defineTheme("hexon", custom.value)
}
watch(
() => custom.value,
() => {
update()
},
{ immediate: true, deep: true }
)
}
Example #29
Source File: manual.ts From vue3-treeview with MIT License | 5 votes |
export default function manual(node: Ref<INode>): IUseCheck {
const checked = computed(() => {
return node.value.state.checked;
});
const indeterminate = computed(() => {
return node.value.state.indeterminate || false;
});
const noneChecked = computed(() => {
return false;
});
const someChecked = computed(() => {
return false;
});
const allChecked = computed(() => {
return false;
});
const someIndeterminate = computed(() => {
return false;
});
const click = (() => {
node.value.state.checked = !node.value.state.checked;
});
const rebuild = (() => {
});
const updateState = (() => {
});
const recurseDown = (() => {
});
return {
checked,
indeterminate,
noneChecked,
someChecked,
allChecked,
someIndeterminate,
click,
rebuild,
updateState,
recurseDown
};
}