<template>
<div>
<h1>{{ message }}</h1>
<button @click="updateMessage">Update Message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue 3!'
};
},
methods: {
updateMessage() {
this.message = 'Updated Message';
}
}
};
</script>
v-bind 绑定属性
<img :src="imageUrl" alt="Image">
v-model 双向绑定
<input v-model="message">
v-for 循环
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
v-if 和 v-else 条件渲染
<div v-if="isVisible">Visible</div>
<div v-else>Hidden</div>
v-show 条件显示
<p v-show="isVisible">This is shown/hidden</p>
生命周期钩子
<script>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
export default {
setup() {
onBeforeMount(() => {
console.log('Before Mount');
});
onMounted(() => {
console.log('Mounted');
});
onBeforeUpdate(() => {
console.log('Before Update');
});
onUpdated(() => {
console.log('Updated');
});
onBeforeUnmount(() => {
console.log('Before Unmount');
});
onUnmounted(() => {
console.log('Unmounted');
});
}
};
</script>
父子组件通信
子组件:
<template>
<button @click="sendToParent">Send to Parent</button>
</template>
<script>
import { defineComponent, ref } from 'vue';
export default defineComponent({
methods: {
sendToParent() {
this.$emit('custom-event', 'Data sent to parent');
}
}
});
</script>
父组件:
<template>
<child-component @custom-event="handleChildEvent"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildEvent(data) {
console.log('Received data from child:', data);
}
}
};
</script>
插槽(Slots)
在这里插入代<template>
<div>
<header>
<slot name="header">Default Header</slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer">Default Footer</slot>
</footer>
</div>
</template>
使用插槽
<my-component>
<template #header>
<h1>Custom Header</h1>
</template>
<p>Main Content</p>
<template #footer>
<p>Custom Footer</p>
</template>
</my-component>
<script>
import { ref, reactive } from 'vue';
export default {
setup() {
const message = ref('Hello, Vue 3!');
const user = reactive({
name: 'John',
age: 25
});
return {
message,
user
};
}
};
</script>
路由(Vue Router)
定义路由
// router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: () => import('./views/About.vue') }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
使用路由
<template>
<router-view></router-view>
</template>