当前位置:首页 > VUE

vue页面实现

2026-03-27 11:43:33VUE

Vue 页面实现基础步骤

安装 Vue.js 项目脚手架
使用 Vue CLI 或 Vite 创建项目,运行命令 npm init vue@latestnpm create vite@latest,根据提示选择 Vue 模板。

创建单文件组件
src/components 目录下新建 .vue 文件,例如 MyComponent.vue,包含 <template><script><style> 三个部分:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

<style scoped>
div {
  color: blue;
}
</style>

路由配置

安装 Vue Router
运行 npm install vue-router,在 src/router/index.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

main.js 中挂载路由:

vue页面实现

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

createApp(App).use(router).mount('#app')

状态管理

使用 Pinia(推荐)
安装:npm install pinia,创建 src/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 store = useCounterStore()
</script>

<template>
  <button @click="store.increment">{{ store.count }}</button>
</template>

生命周期与 API 调用

组合式 API 示例
使用 refonMounted

vue页面实现

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const data = ref(null)

onMounted(async () => {
  const response = await axios.get('https://api.example.com/data')
  data.value = response.data
})
</script>

响应式样式

Scoped CSS 与 CSS 变量
在组件中使用 scoped 样式防止污染:

<style scoped>
.button {
  --primary-color: #42b983;
  background-color: var(--primary-color);
}
</style>

组件通信

父子组件传值
父组件传递 props:

<template>
  <ChildComponent :title="pageTitle" />
</template>

<script setup>
const pageTitle = 'Vue 3 Demo'
</script>

子组件接收:

<script setup>
defineProps(['title'])
</script>

<template>
  <h2>{{ title }}</h2>
</template>

标签: 页面vue
分享给朋友:

相关文章

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue实现盖章

vue实现盖章

Vue 实现盖章功能 在Vue中实现盖章功能通常涉及前端UI交互,通过Canvas或SVG绘制印章,并允许用户拖拽或点击放置印章。以下是具体实现方法: 使用Canvas绘制印章 通过HTML5的Ca…

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…

vue实现白板

vue实现白板

Vue实现白板功能 使用Vue实现白板功能可以通过HTML5的Canvas API结合Vue的响应式特性来完成。以下是实现白板功能的关键步骤: 安装依赖 在Vue项目中安装必要的依赖,如vue-dr…

vue实现树形

vue实现树形

Vue 实现树形组件 在 Vue 中实现树形结构通常需要递归组件和动态数据绑定。以下是实现树形组件的几种常见方法。 递归组件实现 递归组件是 Vue 中实现树形结构的核心方法。通过组件调用自身,可以…