Vue.js 是一个渐进式JavaScript框架,主要用于构建用户界面。它的核心库专注于视图层,易于上手,并且与其他库或已有项目进行整合非常友好。Vue.js 的设计灵活,可以用于从简单的单页应用到复杂的前端项目。
v-bind
、v-if
、v-for
等),用来处理 DOM 的操作。Vue.js 有丰富的生态系统,主要包括:
可以通过 CDN 引入 Vue.js,或者使用 npm 来安装:
<!-- 在 HTML 中通过 CDN 引入 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
或者使用 npm:
npm install vue
下面是一个简单的 Vue.js 应用的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue.js 示例</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<button @click="changeMessage">改变消息</button>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
methods: {
changeMessage() {
this.message = 'Hello, Vue.js!';
}
}
});
</script>
</body>
</html>
Vue.js 提供了双向数据绑定功能,这样可实现数据和视图的同步更新。
<input v-model="message" placeholder="输入内容" />
<p>你输入的内容是:{{ message }}</p>
计算属性是根据现有数据计算得出的属性,可以用来简化模板和提高性能。
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
组件是 Vue.js 的核心概念,组件可以包含自己的模板、数据和方法。
<!-- 父组件 -->
<div id="app">
<my-component></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<div>我是一个组件</div>'
});
new Vue({
el: '#app'
});
</script>
Vue 组件有一些生命周期钩子,可以在不同的阶段执行代码,比如在组件创建前后、更新前后等。
created() {
console.log('组件已创建');
},
mounted() {
console.log('组件已挂载');
}
使用 Vue Router 进行路由管理,设置路由可以通过 VueRouter
:
const Home = { template: '<div>主页</div>' };
const About = { template: '<div>关于</div>' };
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
const app = new Vue({
router
}).$mount('#app');
const Home = { template: '<div>主页</div>' };
const About = { template: '<div>关于</div>' };
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
const app = new Vue({
router
}).$mount('#app');
Vuex 是 Vue 的状态管理库,可以在多个组件之间共享状态。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
}
});
// 组件中使用
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
increment() {
this.$store.commit('increment');
}
}
v-bind
: 动态绑定 HTML 属性v-if
, v-else-if
, v-else
: 条件渲染v-for
: 列表渲染v-show
: 切换元素显示v-model
: 双向数据绑定Vue.js 支持插件机制,可以扩展 Vue 的功能。要使用插件,只需调用 Vue.use()
方法。
Vue.use(VueRouter); // 使用 Vue Router
Vue 3 带来了很多新的特性和优化:
import { createApp, ref } from 'vue';
const app = createApp({
setup() {
const message = ref('Hello Vue 3');
const changeMessage = () => {
message.value = 'Hello from Composition API!';
};
return { message, changeMessage };
}
});
app.mount('#app');