Vue3的基础用法

1. 安装 Vue3
可以通过npm或者yarn安装Vue3:

# 使用npm
npm install vue@next

# 使用yarn
yarn add vue@next

2. 创建Vue应用
在HTML文件中引入 Vue3 的UMD版本,然后创建一个Vue应用:

<!DOCTYPE html>
<html>
<head>
    <title>Vue3 Demo</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="app">
        {{ message }}
    </div>

    <script>
        const app = Vue.createApp({
            data() {
                return {
                    message: 'Hello, Vue3!'
                }
            }
        })
        
        app.mount('#app')
    </script>
</body>
</html>

3. 使用组件
Vue3中可以使用Composition API来定义组件,下面是一个简单的组件示例:

<template>
    <div>
        <h2>{{ title }}</h2>
        <button @click="increaseCount">点击增加</button>
        <p>当前计数:{{ count }}</p>
    </div>
</template>

<script>
    import { ref } from 'vue'

    export default {
        name: 'Counter',
        setup() {
            const title = '计数器'
            const count = ref(0)

            function increaseCount() {
                count.value++
            }

            return {
                title,
                count,
                increaseCount
            }
        }
    }
</script>

4. 组件间通信
Vue3中可以使用provide和inject来进行组件间的通信,比如可以在父组件中provide一个值,然后在子组件中inject来使用这个值:

<!-- ParentComponent.vue -->
<template>
    <div>
        <ChildComponent />
    </div>
</template>

<script>
import { provide } from 'vue'
import ChildComponent from './ChildComponent.vue'

export default {
    name: 'ParentComponent',
    setup() {
        provide('message', 'Hello from parent')
    },
    components: {
        ChildComponent
    }
}
</script>


<!-- ChildComponent.vue -->
<template>
    <div>
        <p>{{ message }}</p>
    </div>
</template>

<script>
import { inject } from 'vue'

export default {
    name: 'ChildComponent',
    setup() {
        const message = inject('message', 'Default message')

        return {
            message
        }
    }
}
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oh-caiii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值