当前位置:首页 > 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 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store 示…

vue分类实现

vue分类实现

Vue分类实现方法 在Vue中实现分类功能通常涉及数据分组、动态渲染和交互逻辑。以下是几种常见的实现方式: 基于计算属性的分类 通过计算属性对原始数据进行分组处理,适合静态或少量数据分类: com…

vue实现全景

vue实现全景

Vue 实现全景效果的方法 使用 Vue 实现全景效果通常需要结合第三方库或框架,以下是几种常见的方法: 使用 Three.js 和 Vue-Three.js Three.js 是一个强大的 3D…

vue实现骰子

vue实现骰子

Vue 实现骰子功能 创建 Vue 组件 在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。 <template> <div class=…

vue实现导出

vue实现导出

Vue 实现导出功能的方法 在 Vue 项目中实现导出功能通常涉及将数据导出为 Excel、CSV 或其他格式。以下是几种常见的实现方式: 使用 xlsx 库导出 Excel 安装 xlsx 库:…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…