vue#SetupContext TypeScript Examples
The following examples show how to use
vue#SetupContext.
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: DatetimeFormat.test.ts From vue-i18n-next with MIT License | 6 votes |
test('component', async () => {
const i18n = createI18n({
locale: 'en-US',
datetimeFormats
})
const MyComponent = defineComponent({
setup(props, context: SetupContext) {
return (): VNodeChild => h('span', context.slots.default!())
}
})
const App = defineComponent({
data: () => ({ MyComponent }),
template: `
<i18n-d :tag="MyComponent" :value="new Date()"></i18n-d>
<i18n-d :tag="MyComponent" :value="new Date()" format="long"></i18n-d>
<i18n-d
:tag="MyComponent"
:value="new Date()"
format="long"
locale="ja-JP-u-ca-japanese"
></i18n-d>
`
})
const wrapper = await mount(App, i18n)
expect(wrapper.html().includes('span')).toBeTruthy()
})
Example #2
Source File: NumberFormat.test.ts From vue-i18n-next with MIT License | 6 votes |
test('component', async () => {
const i18n = createI18n({
locale: 'en-US',
numberFormats
})
const MyComponent = defineComponent({
setup(props, context: SetupContext) {
return (): VNodeChild => h('span', context.slots.default!())
}
})
const App = defineComponent({
data: () => ({ MyComponent }),
template: `
<i18n-n :tag="MyComponent" :value="100"></i18n-n>
<i18n-n :tag="MyComponent" :value="100" format="currency"></i18n-n>
<i18n-n :tag="MyComponent" :value="100" format="currency" locale="ja-JP"></i18n-n>
`
})
const wrapper = await mount(App, i18n)
expect(wrapper.html()).toEqual(
`<span>100</span><span>$100.00</span><span>¥100</span>`
)
})
Example #3
Source File: Translation.test.ts From vue-i18n-next with MIT License | 6 votes |
test('component', async () => {
const i18n = createI18n({
locale: 'en',
messages
})
const MyComponent = defineComponent({
setup(props, context: SetupContext) {
return (): VNodeChild => h('p', context.slots.default!())
}
})
const App = defineComponent({
data: () => ({ MyComponent }),
template: `
<i18n-t :tag="MyComponent" class="name" keypath="message.named">
<template #name>
<span>kazupon</span>
</template>
</i18n-t>
`
})
const wrapper = await mount(App, i18n)
expect(wrapper.html()).toEqual(
`<p class="name">hello, <span>kazupon</span>!</p>`
)
})
Example #4
Source File: formatRenderer.ts From vue-i18n-next with MIT License | 5 votes |
export function renderFormatter<
Props extends FormattableProps<Value, Format>,
Value,
Format extends FormatOverrideOptions,
Arg extends FormatOptions,
Return extends FormatPartReturn
>(
props: Props,
context: SetupContext,
slotKeys: string[],
partFormatter: (...args: unknown[]) => string | Return[]
): RenderFunction {
const { slots, attrs } = context
return (): VNodeChild => {
const options = { part: true } as Arg
let overrides = {} as FormatOverrideOptions
if (props.locale) {
options.locale = props.locale
}
if (isString(props.format)) {
options.key = props.format
} else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString((props.format as any).key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = (props.format as any).key
}
// Filter out number format options only
overrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? assign({}, options, { [prop]: (props.format as any)[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options
}, {})
}
const parts = partFormatter(...[props.value, options, overrides])
let children = [options.key] as VNodeArrayChildren
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type]
const node = slot
? slot({ [part.type]: part.value, index, parts })
: [part.value]
if (isVNode(node)) {
node[0].key = `${part.type}-${index}`
}
return node
})
} else if (isString(parts)) {
children = [parts]
}
const assignedAttrs = assign({}, attrs)
const tag =
isString(props.tag) || isObject(props.tag)
? props.tag
: getFragmentableTag('span')
return h(tag, assignedAttrs, children)
}
}
Example #5
Source File: Translation.test.ts From vue-i18n-next with MIT License | 5 votes |
test('message resolver', async () => {
const fn = jest.fn()
const mockMessageResolver = fn as jest.MockedFunction<MessageResolver>
mockMessageResolver.mockImplementation(
(obj: unknown, path: Path): PathValue => {
const msg = (obj as any)[path] // eslint-disable-line @typescript-eslint/no-explicit-any
return msg != null ? msg : null
}
)
const en = {
'message.named': 'hello, {name}!'
}
const i18n = createI18n({
locale: 'en',
messageResolver: fn,
messages: { en }
})
const MyComponent = defineComponent({
setup(props, context: SetupContext) {
return (): VNodeChild => h('p', context.slots.default!())
}
})
const App = defineComponent({
data: () => ({ MyComponent }),
template: `
<i18n-t :tag="MyComponent" class="name" keypath="message.named">
<template #name>
<span>kazupon</span>
</template>
</i18n-t>
`
})
const wrapper = await mount(App, i18n)
expect(wrapper.html()).toEqual(
`<p class="name">hello, <span>kazupon</span>!</p>`
)
expect(mockMessageResolver).toHaveBeenCalledTimes(1)
expect(mockMessageResolver.mock.calls[0][0]).toEqual(en)
expect(mockMessageResolver.mock.calls[0][1]).toEqual('message.named')
})
Example #6
Source File: useInput.ts From formkit with MIT License | 4 votes |
/**
* A composable for creating a new FormKit node.
* @param type - The type of node (input, group, list)
* @param attrs - The FormKit "props" — which is really the attrs list.
* @returns
* @public
*/
export function useInput(
props: FormKitComponentProps,
context: SetupContext<any>,
options: FormKitOptions = {}
): FormKitNode {
/**
* The configuration options, these are provided by either the plugin or by
* explicit props.
*/
const config = Object.assign({}, inject(optionsSymbol) || {}, options)
/**
* The current instance.
*/
const instance = getCurrentInstance()
/**
* Extracts the listeners.
*/
const listeners = onlyListeners(instance?.vnode.props)
/**
* Determines if the prop is v-modeled.
*/
const isVModeled = props.modelValue !== undefined
/**
* Determines if the object being passed as a v-model is reactive.
*/
// const isReactiveVModel = isVModeled && isReactive(props.modelValue)
/**
* Define the initial component
*/
const value: any =
props.modelValue !== undefined
? props.modelValue
: cloneAny(context.attrs.value)
/**
* Creates the node's initial props from the context, props, and definition
* @returns
*/
function createInitialProps(): Record<string, any> {
const initialProps: Record<string, any> = {
...nodeProps(props),
...listeners,
}
const attrs = except(nodeProps(context.attrs), pseudoProps)
initialProps.attrs = attrs
const propValues = only(nodeProps(context.attrs), pseudoProps)
for (const propName in propValues) {
initialProps[camel(propName)] = propValues[propName]
}
const classesProps = { props: {} }
classesToNodeProps(classesProps as FormKitNode, props)
Object.assign(initialProps, classesProps.props)
if (typeof initialProps.type !== 'string') {
initialProps.definition = initialProps.type
delete initialProps.type
}
return initialProps
}
/**
* Create the FormKitNode.
*/
const initialProps = createInitialProps()
/**
* The parent node.
*/
const parent = initialProps.ignore
? null
: props.parent || inject(parentSymbol, null)
const node = createNode(
extend(
config || {},
{
name: props.name || undefined,
value,
parent,
plugins: (config.plugins || []).concat(props.plugins),
config: props.config,
props: initialProps,
index: props.index,
},
false,
true
) as Partial<FormKitOptions>
) as FormKitNode
/**
* If no definition has been assigned at this point — we're out!
*/
if (!node.props.definition) error(600, node)
/**
* All props that are bound "late" (after node creation) — are added to a set
* which is used to watch the context.attrs object.
*/
const lateBoundProps = ref<Set<string | RegExp>>(
new Set(node.props.definition.props || [])
)
/**
* Any additional props added at a "later" time should also be part of the
* late bound props.
*/
node.on('added-props', ({ payload: lateProps }) => {
if (Array.isArray(lateProps))
lateProps.forEach((newProp) => lateBoundProps.value.add(newProp))
})
/**
* These prop names must be assigned.
*/
const pseudoPropNames = computed(() =>
pseudoProps.concat([...lateBoundProps.value]).reduce((names, prop) => {
if (typeof prop === 'string') {
names.push(camel(prop))
names.push(kebab(prop))
} else {
names.push(prop)
}
return names
}, [] as Array<string | RegExp>)
)
/* Splits Classes object into discrete props for each key */
watchEffect(() => classesToNodeProps(node, props))
/**
* The props object already has properties even if they start as "undefined"
* so we can loop over them and individual watchEffect to prevent responding
* inappropriately.
*/
const passThrough = nodeProps(props)
for (const prop in passThrough) {
watch(
() => props[prop as keyof FormKitComponentProps],
() => {
if (props[prop as keyof FormKitComponentProps] !== undefined) {
node.props[prop] = props[prop as keyof FormKitComponentProps]
}
}
)
}
/**
* Watch "pseudoProp" attributes explicitly.
*/
const attributeWatchers = new Set<WatchStopHandle>()
const possibleProps = nodeProps(context.attrs)
watchEffect(() => {
watchAttributes(only(possibleProps, pseudoPropNames.value))
})
/**
* Defines attributes that should be used as props.
* @param attrProps - Attributes that should be used as props instead
*/
function watchAttributes(attrProps: Record<string, any>) {
attributeWatchers.forEach((stop) => {
stop()
attributeWatchers.delete(stop)
})
for (const prop in attrProps) {
const camelName = camel(prop)
attributeWatchers.add(
watch(
() => context.attrs[prop],
() => {
node.props[camelName] = context.attrs[prop]
}
)
)
}
}
/**
* Watch and dynamically set attribute values, those values that are not
* props and are not pseudoProps
*/
watchEffect(() => {
const attrs = except(nodeProps(context.attrs), pseudoPropNames.value)
node.props.attrs = Object.assign({}, node.props.attrs || {}, attrs)
})
/**
* Add any/all "prop" errors to the store.
*/
watchEffect(() => {
const messages = props.errors.map((error) =>
createMessage({
key: slugify(error),
type: 'error',
value: error,
meta: { source: 'prop' },
})
)
node.store.apply(
messages,
(message) => message.type === 'error' && message.meta.source === 'prop'
)
})
/**
* Add input errors.
*/
if (node.type !== 'input') {
const sourceKey = `${node.name}-prop`
watchEffect(() => {
const keys = Object.keys(props.inputErrors)
const messages = keys.reduce((messages, key) => {
let value = props.inputErrors[key]
if (typeof value === 'string') value = [value]
if (Array.isArray(value)) {
messages[key] = value.map((error) =>
createMessage({
key: error,
type: 'error',
value: error,
meta: { source: sourceKey },
})
)
}
return messages
}, {} as Record<string, FormKitMessage[]>)
node.store.apply(
messages,
(message) =>
message.type === 'error' && message.meta.source === sourceKey
)
})
}
/**
* Watch the config prop for any changes.
*/
watchEffect(() => Object.assign(node.config, props.config))
/**
* Produce another parent object.
*/
if (node.type !== 'input') {
provide(parentSymbol, node)
}
let inputTimeout: number | undefined
// eslint-disable-next-line @typescript-eslint/ban-types
const mutex = new WeakSet<object>()
/**
* Explicitly watch the input value, and emit changes (lazy)
*/
node.on('modelUpdated', () => {
// Emit the values after commit
context.emit('inputRaw', node.context?.value, node)
clearTimeout(inputTimeout)
inputTimeout = setTimeout(
context.emit,
20,
'input',
node.context?.value,
node
) as unknown as number
if (isVModeled && node.context) {
const newValue = useRaw(node.context.value)
if (isObject(newValue) && useRaw(props.modelValue) !== newValue) {
// If this is an object that has been mutated inside FormKit core then
// we know when it is emitted it will "return" in the watchVerbose so
// we pro-actively add it to the mutex.
mutex.add(newValue)
}
context.emit('update:modelValue', newValue)
}
})
/**
* Enabled support for v-model, using this for groups/lists is not recommended
*/
if (isVModeled) {
watchVerbose(toRef(props, 'modelValue'), (path, value): void | boolean => {
const rawValue = useRaw(value)
if (isObject(rawValue) && mutex.has(rawValue)) {
return mutex.delete(rawValue)
}
if (!path.length) node.input(value, false)
else node.at(path)?.input(value, false)
})
}
/**
* When this input shuts down, we need to "delete" the node too.
*/
onUnmounted(() => node.destroy())
return node
}