当前位置:首页 > VUE

简单实现vue

2026-02-10 01:54:15VUE

Vue 3 基础实现示例

以下是一个简单的 Vue 3 实现示例,包含基本功能如数据绑定、事件处理和组件使用。

安装 Vue 3

npm init vue@latest my-vue-app
cd my-vue-app
npm install

创建基础组件

src/components 目录下创建 HelloWorld.vue

<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="increment">Count: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const message = 'Hello Vue 3!';
const count = ref(0);

const increment = () => {
  count.value++;
};
</script>

主入口文件

修改 src/main.js

import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

根组件

修改 src/App.vue

简单实现vue

<template>
  <HelloWorld />
</template>

<script setup>
import HelloWorld from './components/HelloWorld.vue';
</script>

运行项目

启动开发服务器:

npm run dev

响应式数据绑定

Vue 3 使用 refreactive 实现响应式:

<script setup>
import { ref, reactive } from 'vue';

const counter = ref(0);
const user = reactive({
  name: 'John',
  age: 25
});
</script>

条件渲染与列表渲染

<template>
  <div v-if="showMessage">显示消息</div>
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
  </ul>
</template>

生命周期钩子

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  console.log('组件已挂载');
});
</script>

计算属性

<script setup>
import { computed, ref } from 'vue';

const firstName = ref('John');
const lastName = ref('Doe');

const fullName = computed(() => `${firstName.value} ${lastName.value}`);
</script>

组件通信

父组件传递 props:

简单实现vue

<ChildComponent :message="parentMessage" />

子组件接收:

<script setup>
defineProps({
  message: String
});
</script>

状态管理(Pinia)

安装 Pinia:

npm install pinia

创建 store:

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++;
    }
  }
});

组件中使用:

<script setup>
import { useCounterStore } from '@/stores/counter';

const counter = useCounterStore();
</script>

标签: 简单vue
分享给朋友:

相关文章

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端运…

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&…

vue实现阻塞

vue实现阻塞

Vue 实现阻塞的方法 在 Vue 中实现阻塞操作通常涉及异步控制、状态管理或生命周期钩子的使用。以下是几种常见方法: 使用 async/await 处理异步阻塞 通过 async/await 可…

vue实现双击

vue实现双击

Vue 实现双击事件的方法 在Vue中实现双击事件可以通过以下几种方式完成,具体选择取决于项目需求和开发习惯。 使用 @dblclick 指令 Vue提供了内置的@dblclick指令,可以…

vue rooter 实现原理

vue rooter 实现原理

Vue Router 实现原理 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心实现原理包括路由匹配、组件渲染和导航守卫等机制。 路由匹配与动态路由 V…