### Install OMI Package
Source: https://omi.cdn-go.cn/home/latest/introduction
Installs the OMI framework using npm. This is the first step to start using OMI in your project.
```bash
npm i omi
```
--------------------------------
### Implement OMI Component Lifecycle Methods (TSX)
Source: https://omi.cdn-go.cn/home/latest/lifecycle
Demonstrates how to implement lifecycle methods like 'install' and 'uninstall' in an OMI component. This example uses 'setInterval' and 'clearInterval' to manage a timer, updating the component's state and re-rendering.
```tsx
import { render, Component, tag } from 'omi'
@tag('my-timer')
class MyTimer extends Component {
data = {
seconds: 0
}
tick() {
this.data.seconds++
this.update()
}
install() {
this.interval = setInterval(() => this.tick(), 1000)
}
uninstall() {
clearInterval(this.interval)
}
render() {
return
Seconds: {this.data.seconds}
}
}
render(, 'body')
```
--------------------------------
### Define OMI Component with Props (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Demonstrates how to define an OMI component that accepts and renders a 'name' prop. This is a basic example of data transfer to sub-elements.
```tsx
import { Component, define, render } from 'omi'
@tag('my-element')
class MyElement extends Component {
render(props) {
return (
Hello, {props.name}!
)
}
}
```
--------------------------------
### Create a Counter Component with OMI
Source: https://omi.cdn-go.cn/home/latest/introduction
Demonstrates how to create a simple counter component using OMI's JSX syntax, signals for state management, and component lifecycle methods. It includes installation of OMI and usage of render, signal, tag, Component, and h.
```tsx
import { render, signal, tag, Component, h } from 'omi'
const count = signal(0)
function add() {
count.value++
}
function sub() {
count.value--
}
@tag('counter-demo')
class CounterDemo extends Component {
static css = 'span { color: red; }'
render() {
return (
<>
{count.value}
>
)
}
}
render(, document.body)
```
--------------------------------
### Add Mixin to OMI Component (TSX)
Source: https://omi.cdn-go.cn/home/latest/mixin
This example shows how to use the `mixin` function to add a mixin object to an OMI component. The mixin object contains properties that become accessible within the component's instance. This is useful for sharing common logic or state across multiple components.
```tsx
import { tag, Component, h, render, mixin } from 'omi'
mixin({ a: 1 })
@tag('my-app')
class MyApp extends Component {
render() {
// this.a is 1
return
{this.a}
}
}
render(, 'body')
```
--------------------------------
### Basic Slot Implementation in OMI Button (TSX)
Source: https://omi.cdn-go.cn/home/latest/slot
Shows the TSX implementation of an OMI button component that utilizes a slot to render its content. This example illustrates how the tag is used within the render function to accept child content.
```tsx
@tag('o-button')
export default class Button extends Component {
...
...
...
render(props) {
return
}
}
```
--------------------------------
### Accessing DOM Elements with Pre-assigned Refs in OMI TSX
Source: https://omi.cdn-go.cn/home/latest/ref
This example shows an optimized way to handle refs in OMI TSX by pre-assigning the ref callback to a class method. This improves performance by avoiding inline function creation on every render and provides a cleaner way to manage refs.
```tsx
@tag('my-element')
class MyElement extends Component {
onClick = (evt) => {
console.log(this.h1)
}
myRef = e => { this.h1 = e }
render(props) {
return (
Hello, world!
)
}
}
```
--------------------------------
### Bind Click Event using @bind Decorator in OMI (TSX)
Source: https://omi.cdn-go.cn/home/latest/event
This example demonstrates using the `@bind` decorator in OMI to automatically bind the `this` context for event handler methods. This approach simplifies event handling by avoiding the need for arrow functions or manual binding, ensuring `this` correctly refers to the component instance.
```tsx
import { Component, h, bind } from 'omi'
@tag('my-element')
class MyElement extends Component {
@bind
onClick(evt) {
alert('Hello Omi!')
}
render() {
return (
Hello, world!
)
}
}
```
--------------------------------
### Update Component using 'update' Method in OMI (TSX)
Source: https://omi.cdn-go.cn/home/latest/update
Demonstrates how to use the 'update' method within an OMI component to trigger a re-render when the component's state changes. This example shows a counter that increments and updates the UI on button click. It relies on the OMI framework for component definition and rendering.
```tsx
import { tag, Component, h, render } from 'omi'
@tag('hello-omi')
class HelloOmi extends Component {
count = 0
plus = () => {
this.count++
this.update()
}
render(props) {
return (
<>
{this.count}+1
>
)
}
}
render(, 'body')
```
--------------------------------
### Initialize a New OMI Project with Vite
Source: https://omi.cdn-go.cn/home/latest/introduction
Sets up a new OMI project using the OMI CLI with Vite, supporting TypeScript or JavaScript. Includes commands for project initialization, development, and building.
```bash
$ npx omi-cli init my-app # or create js project by: npx omi-cli init-js my-app
$ cd my-app
$ npm start # develop
$ npm run build # release
```
--------------------------------
### Initialize an OMI SPA Project with Vite
Source: https://omi.cdn-go.cn/home/latest/introduction
Creates a new OMI Single Page Application (SPA) project using the OMI CLI, pre-configured with Router, Signal, Suspense, Tailwindcss, Vite, and TypeScript. Includes commands for project initialization, development, and building.
```bash
$ npx omi-cli init-spa my-app
$ cd my-app
$ npm start # develop
$ npm run build # release
```
--------------------------------
### Use OMI Component Directly in HTML
Source: https://omi.cdn-go.cn/home/latest/props
Illustrates how to use an OMI component directly within an HTML body, passing props as attributes. This is applicable when custom elements are used without a framework or with other frameworks.
```html
```
--------------------------------
### Use OMI Component with Props (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Shows how to use a previously defined OMI component, passing a 'name' prop to it. This illustrates the consumption of props passed from a parent or directly in the HTML.
```tsx
```
--------------------------------
### Alternative Text Prop for OMI Button (HTML)
Source: https://omi.cdn-go.cn/home/latest/slot
Provides an alternative HTML method for setting button text using the 'text' prop, which can be used when direct slot content might not be immediately available. This avoids potential user experience issues.
```html
```
--------------------------------
### Scoped CSS with Imported CSS String in OMI
Source: https://omi.cdn-go.cn/home/latest/css
Shows how to import CSS content as a string using Vite's '?raw' import and apply it as scoped CSS to an OMI component. This allows for better organization by keeping styles in separate .css files. Requires Vite for the raw import functionality.
```tsx
import cssString from './xxx.css?raw'
@tag('my-element')
class MyElement extends Component {
// Scoped CSS
static css = cssString
...
...
}
```
--------------------------------
### Listen to OMI Component Lifecycle Events (TSX)
Source: https://omi.cdn-go.cn/home/latest/lifecycle
Shows how to listen to lifecycle events, such as 'onInstalled', directly on a component tag within another OMI component. The event detail provides access to the component instance that emitted the event.
```tsx
import { render, Component, tag } from 'omi'
@tag('my-element')
class MyElement extends Component {
render() {
return
el
}
}
@tag('my-app')
class MyElement extends Component {
render() {
return (
{
updateMenu(evt.detail)
}}>
)
}
}
render(, 'body')
```
--------------------------------
### Basic Slot Usage in OMI Button (HTML)
Source: https://omi.cdn-go.cn/home/latest/slot
Demonstrates how to use a default slot in an OMI button component to render button text. The content within the o-button tags is placed into the slot.
```html
I'm button text
```
--------------------------------
### Define OMI Component with Default and Typed Props (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Shows how to define default values for props ('name', 'myAge') and specify their types using 'static defaultProps' and 'static propTypes'. This enhances component robustness and predictability.
```tsx
@tag('my-element')
class MyElement extends Component {
static defaultProps = {
name: 'Omi',
myAge: 18
}
// It's not mandatory to define propTypes. You only need to define them when you are writing components using Omi independently.
static propTypes = {
name: String,
myAge: Number,
// Also supports multiple types of attributes
color: [String, Array]
}
render(props) {
return (
Hello, {props.name}! Age {props.myAge}
)
}
}
```
--------------------------------
### Listen for Custom Event Imperatively using addEventListener (JavaScript)
Source: https://omi.cdn-go.cn/home/latest/event
This JavaScript snippet demonstrates how to listen for a custom event ('my-event') on an OMI component using the standard `addEventListener` method. This imperative approach is useful when dynamic event handling is required or when working outside of JSX.
```js
myElement.addEventListener('my-event', (evt) => {})
```
--------------------------------
### Sharing and Overriding Styles in OMI Components
Source: https://omi.cdn-go.cn/home/latest/css
Illustrates how to define and share CSS styles across multiple OMI components using the `css` tagged template literal. It also shows how to override or stack shared styles within individual components. This promotes reusability and maintainability of styles.
```tsx
import { render, tag, Component, h, css } from 'omi'
// Define shared styles
const style = css`p { color: green; }`
@tag('el-a')
class ElA extends Component {
static css = [style]
render() {
return (
<>
>
)
}
}
```
--------------------------------
### Create a Signal in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Demonstrates how to create a signal object, which wraps a value and allows for observation and modification. When the signal's value changes, it notifies dependent functions. The signal function is used for creation.
```typescript
const counter = signal(0);
```
--------------------------------
### Provide Data in OMI Parent Component (TSX)
Source: https://omi.cdn-go.cn/home/latest/provide-inject
Demonstrates how to use the `provide` option in an OMI parent component to make data available to its descendants. This is useful for avoiding prop drilling across multiple component levels. The `provide` object maps the data keys to their values.
```tsx
@tag('parent-el')
class MyElement extends Component {
provide = {
name: 'omi'
}
render() {
return
}
}
```
```tsx
@tag('parent-el')
class MyElement extends Component {
provide = {
name: 'omi'
}
render() {
return
}
}
```
--------------------------------
### Define OMI Component with Object Prop (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Illustrates defining an OMI component that accepts an object prop (myObj) and accesses its properties. This showcases passing complex data structures as props.
```tsx
@tag('my-element')
class MyElement extends Component {
render(props) {
return (
Hello, {props.myObj.name}!
)
}
}
```
--------------------------------
### Merge Prop Definitions in OMI (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Demonstrates merging prop definitions, including type, default value, and a change handler, into a single 'static props' object. This approach simplifies prop management for complex components.
```tsx
static props = {
count: {
type: Number,
default: 0,
changed(newValue, oldValue) {
this.state.count = newValue
this.update()
}
}
}
```
--------------------------------
### Named Slot Usage in OMI Element (HTML)
Source: https://omi.cdn-go.cn/home/latest/slot
Demonstrates the usage of named slots within an OMI element. Spans with the 'slot' attribute are directed to specific named slots within the component definition.
```html
```
--------------------------------
### Scoped CSS with Direct String in OMI
Source: https://omi.cdn-go.cn/home/latest/css
Demonstrates how to apply scoped CSS directly within an OMI component using a static 'css' property. This method prevents style pollution by isolating styles to the component. No external dependencies are needed for this basic usage.
```tsx
import { Component, h } from 'omi'
@tag('my-element')
class MyElement extends Component {
// Scoped CSS
static css = 'h1 { color: red }'
render() {
return (
Hello, world!
)
}
}
```
--------------------------------
### Use OMI Component with Object Prop (TSX)
Source: https://omi.cdn-go.cn/home/latest/props
Demonstrates using an OMI component and passing an object literal as a prop. This is useful for passing multiple related values to a component.
```tsx
```
--------------------------------
### Create an Effect to Track Signal Dependencies in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Demonstrates how to use the `effect` function to track changes in signal values. When a signal's value is accessed within an effect, the effect function automatically reruns upon signal updates. The `dispose` function stops this tracking.
```typescript
const counter = signal(0)
const dispose = effect(() => {
console.log(`Counter:${counter.value}`)
})
// Stop tracking dependencies
dispose()
```
--------------------------------
### Use update() to Trigger Effect for Array Mutations in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Shows how to use the `update()` method to manually trigger an effect when a signal's value has been mutated (e.g., pushing to an array) without reassigning the signal. This ensures effects re-run even for in-place modifications.
```typescript
const testSignal = signal([1,2,3])
let effectTimes = 0
effect(() => {
console.log(testSignal.value)
effectTimes++
})
testSignal.value.push(4)
// Like testSignal.value = testSignal.value, it will trigger effect
testSignal.update()
expect(effectTimes).toBe(2)
```
--------------------------------
### OMI Prop Type Definition (TypeScript)
Source: https://omi.cdn-go.cn/home/latest/props
Provides the TypeScript type definition for OMI props, outlining the structure for defining prop types, default values, reflection, and change handlers. This is essential for type safety in TypeScript projects.
```ts
type PropType = String | Number | Boolean | Array | Object | Array;
type Props = {
[key: string]: {
type?: PropType;
default?: any;
reflect?: boolean | ((value: any) => any);
changed?: (newValue: any, oldValue: any) => void;
}
}
```
--------------------------------
### Register and Use OMI Custom Directive (TSX)
Source: https://omi.cdn-go.cn/home/latest/directive
Demonstrates how to register a custom directive named 'test' in OMI, which applies CSS styles to an element. The directive is then used within a component to modify the style of a div element. This functionality requires the 'omi' library.
```tsx
import { tag, render, Component, registerDirective, h } from 'omi'
registerDirective('test', (el, exp) => {
el.style.cssText = exp
})
@tag('my-app')
class MyApp extends Component {
static css = `div {color: red;}`
render() {
return (
Hello Omi!
)
}
}
render(, 'body')
```
--------------------------------
### Use Omi Component in Vue 3 (Vue)
Source: https://omi.cdn-go.cn/home/latest/cross-frameworks
Integrates the 'my-counter' Omi component into a Vue 3 application. It imports the Omi component and uses Vue's reactivity system to manage the count, listening for the 'change' event emitted by the Omi component.
```vue
{{ msg }}
【Omi】
【Vue】
```
--------------------------------
### Named Slot Implementation in OMI Element (TSX)
Source: https://omi.cdn-go.cn/home/latest/slot
Illustrates the TSX implementation of an OMI component that supports named slots. The component defines multiple elements, each with a 'name' attribute corresponding to the slot names used in the HTML.
```tsx
@tag('o-el')
export default class Button extends Component {
render(props) {
return
Some Info
}
}
```
--------------------------------
### Listen for Custom Event Declaratively in OMI (TSX)
Source: https://omi.cdn-go.cn/home/latest/event
This code shows how to listen for a custom event ('my-event') emitted by an OMI component using declarative event binding within JSX. The `onMyEvent` attribute is used, and the event handler accesses the custom event's detail payload.
```tsx
{ alert(evt.detail.name) }}>
```
--------------------------------
### Accessing DOM Elements with createRef in OMI
Source: https://omi.cdn-go.cn/home/latest/ref
This snippet illustrates using `createRef` to manage refs in OMI components. `createRef` provides a more structured approach, where the DOM element is accessed via `this.myRef.current`, similar to React's ref pattern.
```tsx
define('my-element', class extends Component {
onClick = (evt) => {
console.log(this.myRef.current) //h1
}
myRef = createRef()
render(props) {
return (
Hello, world!
)
}
})
```
--------------------------------
### Define a Counter Component with Omi (JavaScript)
Source: https://omi.cdn-go.cn/home/latest/cross-frameworks
This snippet defines a custom Omi component named 'my-counter'. It manages a count state, allows incrementing and decrementing, and emits a 'change' event. It uses standard JavaScript and Omi's h function for rendering.
```javascript
import { define, Component, h } from 'omi'
define('my-counter', class extends Component {
static props = {
count: {
type: Number,
default: 0,
changed(newValue, oldValue) {
this.state.count = newValue
this.update()
}
}
}
state = {
count: null
}
install() {
this.state.count = this.props.count
}
sub = () => {
this.state.count--
this.update()
this.fire('change', this.state.count)
}
add = () => {
this.state.count++
this.update()
this.fire('change', this.state.count)
}
render(props) {
return [
h('button', { onClick: this.sub }, '-'),
h('span', null, this.state.count),
h('button', { onClick: this.add }, '+')
]
}
})
```
```javascript
import { define, Component, h } from 'omi'
define('my-counter', class extends Component {
static props = {
count: {
type: Number,
default: 0,
changed(newValue, oldValue) {
this.state.count = newValue
this.update()
}
}
}
state = {
count: null
}
install() {
this.state.count = this.props.count
}
sub = () => {
this.state.count--
this.update()
this.fire('change', this.state.count)
}
add = () => {
this.state.count++
this.update()
this.fire('change', this.state.count)
}
render(props) {
return [
h('button', { onClick: this.sub }, '-'),
h('span', null, this.state.count),
h('button', { onClick: this.add }, '+')
]
}
})
```
--------------------------------
### Inject Data in OMI Child Component (TSX)
Source: https://omi.cdn-go.cn/home/latest/provide-inject
Illustrates how to use the `inject` option in an OMI descendant component to access data provided by an ancestor. Any descendant component can inject provided data, simplifying data flow. The injected data is accessed via `this.injection`.
```tsx
@tag('child-el')
class MyElement extends Component {
inject = ['name']
render() {
//output:
}
}
```
--------------------------------
### Fire Custom Event from OMI Component (TSX)
Source: https://omi.cdn-go.cn/home/latest/event
This snippet illustrates how to create and fire a custom event named 'my-event' from an OMI component. The `this.fire` method is used, passing the event name and an optional data payload. The data is accessible via `evt.detail` on the listening side.
```tsx
@tag('my-element')
class MyElement extends Component {
onClick = (evt) => {
this.fire('my-event', { name: 'abc' })
}
render(props) {
return (
Hello, world!
)
}
}
```
--------------------------------
### Use peek() to Access Signal Value Without Triggering Dependencies in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Explains the `peek()` method for accessing a signal's value within a computed property or effect without causing the dependent function to re-run. This is useful for optimizing updates.
```typescript
const name = signal('Dnt')
const surname = signal('Zhang')
const fullName = computed(() => name.peek() + ' ' + surname.value)
let effectTimes = 0
effect(() => {
// Accessing fullName.value will trigger dependency
fullName.value
effectTimes++
})
name.value = 'John'
// Because peek does not trigger dependency, effectTimes is still 1
expect(effectTimes).toBe(1)
```
--------------------------------
### Use Omi Component in React (TSX)
Source: https://omi.cdn-go.cn/home/latest/cross-frameworks
Integrates the 'my-counter' Omi component into a React application using hooks. It utilizes `useState` for managing the count and `useRef` to access the Omi component instance, adding an event listener for the 'change' event.
```tsx
import { useState, useRef, useEffect } from 'react'
import useEventListener from '@use-it/event-listener'
import './my-counter'
function App() {
const [count, setCount] = useState(100)
const myCounterRef = useRef(null)
useEffect(() => {
const counter = myCounterRef.current
if (counter) {
const handleChange = (evt) => {
setCount(evt.detail)
}
counter.addEventListener('change', handleChange)
return () => {
counter.removeEventListener('change', handleChange)
}
}
}, [])
return (
<>
Omi + React
>
)
}
export default App
```
--------------------------------
### Access and Modify Signal Value in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Shows how to access and modify the value held within a signal object using the `.value` property. This operation is fundamental for interacting with reactive data.
```typescript
console.log(counter.value); // Outputs 0
```
--------------------------------
### Create a Computed Signal in TypeScript
Source: https://omi.cdn-go.cn/home/latest/reactivity
Illustrates the creation of a computed signal, which derives its value from other signals. When dependent signals change, the computed signal automatically updates. The `computed` function is used for this purpose.
```typescript
const counter = signal(0);
const doubledCounter = computed(() => counter.value * 2);
console.log(doubledCounter.value); // Outputs 0
counter.value = 1;
console.log(doubledCounter.value); // Outputs 2
```
--------------------------------
### Define Omi Counter Component (TSX)
Source: https://omi.cdn-go.cn/home/latest/cross-frameworks
Defines a reusable 'my-counter' component using Omi's tag system. It includes properties for 'count', internal state management, and methods to increment/decrement the count, firing a 'change' event. This component can be used in various frameworks.
```tsx
import { tag, Component, h, bind } from 'omi'
@tag('my-counter')
class MyCounter extends Component {
static props = {
count: {
type: Number,
default: 0,
changed(newValue, oldValue) {
this.state.count = newValue
this.update()
}
}
}
state = {
count: null
}
install() {
this.state.count = this.props.count
}
@bind
sub() {
this.state.count--
this.update()
this.fire('change', this.state.count)
}
@bind
add() {
this.state.count++
this.update()
this.fire('change', this.state.count)
}
render() {
return (
<>
{this.state.count}
>
)
}
}
```
--------------------------------
### Bind Click Event to Element in OMI (TSX)
Source: https://omi.cdn-go.cn/home/latest/event
This snippet shows how to bind a click event to an HTML element within an OMI component using an arrow function. When the element is clicked, an alert message is displayed. This is a common pattern for handling user interactions.
```tsx
import { Component, h } from 'omi'
@tag('my-element')
class MyElement extends Component {
onClick = (evt) => {
alert('Hello Omi!')
}
render() {
return (
Hello, world!
)
}
}
```
--------------------------------
### Accessing DOM Elements with Inline Refs in OMI TSX
Source: https://omi.cdn-go.cn/home/latest/ref
This snippet demonstrates how to attach a ref directly to a DOM element within the render method in OMI's TSX syntax. The ref is assigned to a class property, allowing access to the DOM node via `this.h1` in event handlers.
```tsx
@tag('my-element')
class MyElement extends Component {
onClick = (evt) => {
console.log(this.h1)
}
render(props) {
return (
{ this.h1 = e }} onClick={this.onClick}>Hello, world!
)
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.