1. Vue 基础
- 数据绑定与响应式原理
Vue 通过数据劫持和发布 - 订阅者模式实现数据的响应式。在 Vue 实例中定义的数据,当数据变化时,与之绑定的视图会自动更新。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 数据绑定</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
<button @click="changeMessage">改变信息</button>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: '初始信息'
},
methods: {
changeMessage: function () {
this.message = '信息已改变';
}
}
});
</script>
</body>
</html>
在上述代码中,{{ message }} 将 data 中的 message 数据绑定到视图。点击按钮时,changeMessage 方法修改 message,视图会自动更新。
2. 生命周期钩子函数
生命周期钩子函数在 Vue 实例的不同阶段被调用,方便执行特定逻辑。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 生命周期</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: '初始信息'
},
created() {
console.log('Vue 实例已创建,此时数据已初始化:', this.message);
},
mounted() {
console.log('Vue 实例已挂载到 DOM,此时可以操作 DOM 元素');
},
updated() {
console.log('数据更新,视图已重新渲染');
},
beforeDestroy() {
console.log('Vue 实例即将销毁,可进行清理操作');
}
});
setTimeout(() => {
app.$destroy();
}, 3000);
</script>
</body>
</html>
created 钩子函数在实例创建完成后调用,此时数据已初始化。mounted 在模板编译挂载到 DOM 后调用。updated 在数据更新导致视图重新渲染后调用。beforeDestroy 在实例销毁前调用。
3. 模板语法
文本插值:使用 {{ }} 插入数据。
指令:如 v - if、v - for、v - bind、v - on 等。
计算属性:基于已有数据进行计算得出新数据。
侦听器:监听数据变化并执行相应操作。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 模板语法</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 文本插值 -->
<p>{{ message }}</p>
<!-- v - if 指令 -->
<p v - if="isShow">条件为真时显示</p>
<!-- v - for 指令 -->
<ul>
<li v - for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
<!-- v - bind 指令 -->
<img :src="imageSrc" alt="图片">
<!-- v - on 指令 -->
<button @click="handleClick">点击我</button>
<!-- 计算属性 -->
<p>计算属性结果: {{ reversedMessage }}</p>
<!-- 侦听器 -->
<input v - model="inputValue">
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue',
isShow: true,
items: ['苹果', '香蕉', '橙子'],
imageSrc: 'https://example.com/image.jpg',
inputValue: ''
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
},
methods: {
handleClick() {
this.message = '按钮被点击了';
}
},
watch: {
inputValue(newValue, oldValue) {
console.log('输入值变化了,旧值:', oldValue, '新值:', newValue);
}
}
});
</script>
</body>
</html>
v - if 根据 ishow 的值决定是否显示 p 元素。
v - for 遍历 items 数组并渲染列表。
v - bind 动态绑定 src 属性。
v - on 绑定点击事件。
计算属性 reversedMessage 对 message 进行反转。
侦听器 watch 监听 inputValue 的变化。
2. 组件系统
- 组件定义与使用
全局组件:使用 Vue.component() 定义,可在任何 Vue 实例中使用。
局部组件:在 components 选项中定义,只能在当前组件的模板中使用。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 使用全局组件 -->
<my - global - component></my - global - component>
<!-- 使用局部组件 -->
<my - local - component></my - local - component>
</div>
<script>
// 全局组件定义
Vue.component('my - global - component', {
template: '<p>这是一个全局组件</p>'
});
const app = new Vue({
el: '#app',
components: {
// 局部组件定义
'my - local - component': {
template: '<p>这是一个局部组件</p>'
}
}
});
</script>
</body>
</html>
- 组件通信
父子组件通信:父组件通过 props 向子组件传递数据,子组件通过 $emit 触发自定义事件向父组件传递数据。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>父子组件通信</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child - component :parent - data="parentData" @child - event="handleChildEvent"></child - component>
</div>
<script>
const ChildComponent = {
props: ['parentData'],
template: `
<div>
<p>父组件传递的数据: {{ parentData }}</p>
<button @click="sendDataToParent">传递数据给父组件</button>
</div>
`,
methods: {
sendDataToParent() {
this.$emit('child - event', '子组件的数据');
}
}
};
const app = new Vue({
el: '#app',
data: {
parentData: '初始父组件数据'
},
components: {
'child - component': ChildComponent
},
methods: {
handleChildEvent(data) {
console.log('接收到子组件的数据:', data);
this.parentData = data;
}
}
});
</script>
</body>
</html>
父组件通过 :parent - data 将 parentData 传递给子组件,子组件通过 @child - event 触发的事件将数据传递回父组件。
3. 指令
内置指令
条件渲染指令:v - if、v - else、v - else - if、v - show。
列表渲染指令:v - for。
属性绑定指令:v - bind(简写 :)。
事件绑定指令:v - on(简写 @)。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 内置指令</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- v - if 指令 -->
<p v - if="isTrue">条件为真时显示</p>
<p v - else>条件为假时显示</p>
<!-- v - for 指令 -->
<ul>
<li v - for="(num, index) in numbers" :key="index">{{ num }}</li>
</ul>
<!-- v - bind 指令 -->
<a :href="link">点击跳转</a>
<!-- v - on 指令 -->
<button @click="increment">点击增加</button>
<p>计数: {{ count }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
isTrue: true,
numbers: [1, 2, 3, 4, 5],
link: 'https://www.example.com',
count: 0
},
methods: {
increment() {
this.count++;
}
}
});
</script>
</body>
</html>
v - if 根据 isTrue 的真假决定是否显示 <p> 元素。v - for 遍历 numbers 数组渲染列表。v - bind 动态绑定 href 属性。v - on 绑定点击事件实现计数功能。
自定义指令
通过 Vue.directive() 定义自定义指令,可复用 DOM 操作。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue 自定义指令</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input v - focus>
</div>
<script>
Vue.directive('focus', {
inserted: function (el) {
el.focus();
}
});
const app = new Vue({
el: '#app'
});
</script>
</body>
</html>
上述代码定义了 v - focus 自定义指令,在元素插入 DOM 时自动获取焦点。
4. Vuex 状态管理
- 核心概念
State:存储应用状态。
Getter:从 State 派生数据。
Mutation:同步修改 State。
Action:处理异步操作并提交 Mutation。
Module:拆分状态管理。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vuex 示例</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuex/dist/vuex.js"></script>
</head>
<body>
<div id="app">
<p>计数器: {{ count }}</p>
<button @click="increment">增加</button>
<button @click="incrementAsync">异步增加</button>
</div>
<script>
// 创建 Vuex store
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
doubleCount(state) {
return state.count * 2;
}
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
});
const app = new Vue({
el: '#app',
computed: {
count() {
return store.state.count;
}
},
methods: {
increment() {
store.commit('increment');
},
incrementAsync() {
store.dispatch('incrementAsync');
}
}
});
</script>
</body>
</html>
state 中的 count 是应用状态。getters 中的 doubleCount 从 count 派生数据。mutations 中的 increment 同步修改 count。actions 中的 incrementAsync 异步操作后提交 increment mutation。
5. Vue Router
- 路由定义与配置
通过 VueRouter 插件定义路由规则。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue Router 示例</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue - router/dist/vue - router.js"></script>
</head>
<body>
<div id="app">
<router - link to="/home">首页</router - link>
<router - link to="/about">关于</router - link>
<router - view></router - view>
</div>
<script>
const Home = {
template: '<p>这是首页</p>'
};
const About = {
template: '<p>这是关于页面</p>'
};
const router = new VueRouter({
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
});
const app = new Vue({
el: '#app',
router
});
</script>
</body>
</html>
- routes 数组定义了路由规则,router - link 创建导航链接,router - view 显示匹配路由的组件。
路由模式
- Hash 模式:URL 包含 #,如 http://example.com/#/home。
- History 模式:利用 HTML5 历史 API,URL 更美观,如 http://example.com/home,但需后端配置支持。
// History 模式配置
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
});
//路由导航
//除了 router - link,还可通过编程式导航。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>Vue Router 导航</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue - router/dist/vue - router.js"></script>
</head>
<body>
<div id="app">
<button @click="goToHome">跳转到首页</button>
<router - view></router - view>
</div>
<script>
const Home = {
template: '<p>这是首页</p>'
};
const router = new VueRouter({
routes: [
{ path: '/home', component: Home }
]
});
const app = new Vue({
el: '#app',
router,
methods: {
goToHome() {
this.$router.push('/home');
}
}
});
</script>
</body>
</html>
this.$router.push(‘/home’) 实现编程式导航到首页。
6. 项目结构
典型的 Vue 项目结构如下:
plaintext
project - root
├── src
│ ├── assets
│ │ ├── images
│ │ │ └── logo.png
│ │ └── styles
│ │ └── main.css
│ ├── components
│ │ ├── Button.vue
│ │ └── Input.vue
│ ├── router
│ │ └── index.js
│ ├── store
│ │ ├── index.js
│ │ └── modules
│ │ └── user.js
│

被折叠的 条评论
为什么被折叠?



