实现vue
安装Vue.js
通过npm安装Vue.js是最常见的方式。确保已安装Node.js和npm,运行以下命令:
npm install vue
对于快速原型开发或学习,可以直接通过CDN引入:
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
创建Vue实例
在HTML中定义一个挂载点,通常是一个div元素:
<div id="app">{{ message }}</div>
在JavaScript中创建Vue实例并绑定到挂载点:
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
使用Vue CLI搭建项目
Vue CLI是官方提供的脚手架工具,适合构建大型项目。全局安装Vue CLI:
npm install -g @vue/cli
创建新项目:
vue create my-project
进入项目目录并启动开发服务器:
cd my-project
npm run serve
基本模板语法
Vue使用双大括号插值显示数据:
<span>{{ message }}</span>
使用v-bind指令绑定属性:
<div v-bind:class="{ active: isActive }"></div>
简写形式:
<div :class="{ active: isActive }"></div>
条件渲染
使用v-if指令根据条件渲染元素:
<p v-if="seen">现在你看到我了</p>
v-else和v-else-if提供更多条件分支:

<div v-if="type === 'A'">A</div>
<div v-else-if="type === 'B'">B</div>
<div v-else>C</div>
列表渲染
使用v-for指令渲染列表:
<ul>
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</ul>
事件处理
使用v-on指令监听DOM事件:
<button v-on:click="greet">Greet</button>
简写形式:
<button @click="greet">Greet</button>
计算属性和侦听器
计算属性基于依赖缓存,适合复杂逻辑:
computed: {
reversedMessage: function () {
return this.message.split('').reverse().join('')
}
}
侦听器适合异步或开销较大的操作:
watch: {
question: function (newQuestion, oldQuestion) {
this.getAnswer()
}
}
组件系统
定义全局组件:
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
在模板中使用组件:

<my-component></my-component>
单文件组件
Vue单文件组件(.vue文件)将模板、脚本和样式封装在一个文件中:
<template>
<div class="example">{{ msg }}</div>
</template>
<script>
export default {
data () {
return {
msg: 'Hello world!'
}
}
}
</script>
<style>
.example {
color: red;
}
</style>
状态管理(Vuex)
安装Vuex:
npm install vuex --save
创建store:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
在组件中使用:
this.$store.commit('increment')
console.log(this.$store.state.count)
路由(Vue Router)
安装Vue Router:
npm install vue-router
配置路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home }
]
const router = new VueRouter({
routes
})
在组件中使用路由:
<router-link to="/">Home</router-link>
<router-view></router-view>






