1. 安装 Vue.js 3
可以通过 CDN 或 npm 安装 Vue.js 3。如果使用 CDN,可以在 HTML 文件中引入以下脚本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 3 Tutorial</title>
<script src="https://cdn.jsdelivr.net/npm/vue@next"></script>
</head>
<body>
<div id="app">
{{ message }}
</div>
<script>
// 在这里编写你的 Vue 3 代码
</script>
</body>
</html>
如果使用 npm,可以通过以下命令安装:
npm install vue@next
2. 创建 Vue 实例
在你的 JavaScript 文件中,创建一个 Vue 实例:
const app = Vue.createApp({
data() {
return {
message: 'Hello, Vue 3!'
};
}
});
app.mount('#app');
3. 使用 Vue 模板
在 HTML 文件中,使用 Vue 的模板语法来渲染数据:
<div id="app">
{{ message }}
</div>
4. 数据绑定
Vue 3 使用 v-bind 指令进行数据绑定。例如,将一个属性绑定到元素的 class:
<div :class="{ active: isActive }">This is a dynamic class</div>
5. 事件处理
使用 v-on 指令来监听事件,例如点击事件:
<button @click="handleClick">Click me</button>
在 Vue 实例中定义对应的方法:
const app = Vue.createApp({
methods: {
handleClick() {
alert('Button clicked!');
}
}
});
6. 条件和循环
使用 v-if 和 v-for 来进行条件渲染和循环渲染:
<div v-if="isDisplayed">This element is displayed</div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
7. 组件
Vue 3 支持组件化开发。定义一个组件:
app.component('my-component', {
template: '<div>My Component</div>'
});
在模板中使用组件:
<my-component></my-component>
8. 生命周期钩子
Vue 3 的生命周期钩子包括 beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, 和 unmounted。
const app = Vue.createApp({
beforeCreate() {
console.log('Before Create Hook');
},
created() {
console.log('Created Hook');
},
mounted() {
console.log('Mounted Hook');
}
});
app.mount('#app');
这是一个简单的 Vue.js 3 入门教程。Vue 3 的文档提供了更详细的信息,你可以在[官方文档](https://v3.vuejs.org/)中深入学习。
转载请注明出处:http://www.zyzy.cn/article/detail/12969/Vue3