vue网页实现
Vue 网页实现基础步骤
安装 Vue.js
通过 npm 或 CDN 引入 Vue.js。npm 安装命令:npm install vue。CDN 引入方式:<script src="https://cdn.jsdelivr.net/npm/vue@3.2.31/dist/vue.global.js"></script>。
创建 Vue 实例
在 HTML 中定义挂载点(如 <div id="app"></div>),通过 JavaScript 初始化 Vue 实例:
const app = Vue.createApp({
data() {
return { message: 'Hello Vue!' }
}
}).mount('#app')
数据绑定与模板语法
双大括号插值
在 HTML 模板中使用 {{ }} 绑定数据:
<div id="app">{{ message }}</div>
指令绑定
使用 v-bind 绑定属性(可简写为 :):
<img :src="imageSrc" alt="Vue Logo">
条件与循环渲染
条件渲染
通过 v-if 或 v-show 控制元素显示:
<p v-if="isVisible">显示内容</p>
列表渲染
使用 v-for 渲染数组:
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
事件处理
方法绑定
通过 v-on 监听事件(可简写为 @):
<button @click="handleClick">点击</button>
事件修饰符
使用修饰符如 .prevent 阻止默认行为:
<form @submit.prevent="onSubmit"></form>
组件化开发
定义组件
创建可复用的 Vue 组件:

app.component('todo-item', {
props: ['title'],
template: `<li>{{ title }}</li>`
})
组件通信
父组件通过 props 传递数据,子组件通过 $emit 触发事件:
// 父组件
<child-component :msg="parentMsg" @update="handleUpdate"/>
// 子组件
this.$emit('update', newValue)
状态管理(Vuex)
安装 Vuex
通过 npm 安装:npm install vuex。
创建 Store
定义集中式状态管理:
import { createStore } from 'vuex'
const store = createStore({
state: { count: 0 },
mutations: {
increment(state) {
state.count++
}
}
})
组件中使用
通过 this.$store 访问状态或提交变更:
this.$store.commit('increment')
console.log(this.$store.state.count)
路由配置(Vue Router)
安装 Vue Router
通过 npm 安装:npm install vue-router@4。

定义路由
创建路由实例并映射组件:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
路由视图
在模板中使用 <router-view> 显示匹配组件:
<router-view></router-view>
样式与静态资源
Scoped CSS
组件样式作用域限制:
<style scoped>
.button { color: red; }
</style>
静态资源处理
通过 @ 别名引用 src 目录下的资源:
<img src="@/assets/logo.png">
构建与部署
开发环境
使用 Vue CLI 或 Vite 启动开发服务器:
npm run dev
生产构建
生成优化后的静态文件:
npm run build
部署
将 dist 目录内容上传至 Web 服务器(如 Nginx、Netlify 等)。






