怎么使用vue3的语法
时间: 2024-04-30 21:23:24 浏览: 8
使用Vue3的语法需要先安装Vue3。
1. 安装Vue3
使用npm安装Vue3:
```bash
npm install vue@next
```
或者使用yarn安装:
```bash
yarn add vue@next
```
2. 创建Vue3实例
```html
<div id="app"></div>
```
```js
import { createApp } from 'vue'
const app = createApp({
data() {
return {
message: 'Hello Vue 3!'
}
}
})
app.mount('#app')
```
3. 数据绑定
```html
<div id="app">
<p>{{ message }}</p>
</div>
```
```js
import { createApp } from 'vue'
const app = createApp({
data() {
return {
message: 'Hello Vue 3!'
}
}
})
app.mount('#app')
```
4. 条件渲染
```html
<div id="app">
<template v-if="show">
<p>{{ message }}</p>
</template>
<button @click="toggleShow">{{ show ? '隐藏' : '显示' }}</button>
</div>
```
```js
import { createApp, ref } from 'vue'
const app = createApp({
setup() {
const message = ref('Hello Vue 3!')
const show = ref(true)
const toggleShow = () => {
show.value = !show.value
}
return {
message,
show,
toggleShow
}
}
})
app.mount('#app')
```
5. 循环渲染
```html
<div id="app">
<ul>
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
</div>
```
```js
import { createApp, ref } from 'vue'
const app = createApp({
setup() {
const list = ref(['Apple', 'Banana', 'Orange'])
return {
list
}
}
})
app.mount('#app')
```
6. 事件绑定
```html
<div id="app">
<button @click="count++">{{ count }}</button>
</div>
```
```js
import { createApp, ref } from 'vue'
const app = createApp({
setup() {
const count = ref(0)
return {
count
}
}
})
app.mount('#app')
```
7. 组件
```html
<div id="app">
<hello-world></hello-world>
</div>
```
```js
import { createApp } from 'vue'
const HelloWorld = {
template: '<p>Hello World!</p>'
}
const app = createApp({
components: {
HelloWorld
}
})
app.mount('#app')
```