Vue.js 是一款渐进式JavaScript框架,它易于上手,功能富强,合适构建用户界面。经由过程本文,你将懂得Vue.js的基本知识,并经由过程实战案例进修怎样将其利用于现实项目中。
Vue.js 是一个用于构建用户界面的库,它采取组件化的头脑,容许开辟者将UI拆分红独破、可复用的组件。Vue.js 的核心库只关凝视图层,易于上手,同时也可能与其余库或已有项目集成。
Vue.js 须要Node.js情况,因此起首须要安装Node.js。
# 经由过程npm安装Node.js
npm install -g nvm
nvm install node
Vue CLI 是一个官方命令行东西,用于疾速搭建Vue项目。
# 经由过程npm安装Vue CLI
npm install -g @vue/cli
Vue.js 利用<template>
, <script>
, <style>
三个标签来定义组件。
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Hello Vue!'
};
}
}
</script>
<style scoped>
h1 {
color: red;
}
</style>
在Vue实例中注册组件。
new Vue({
el: '#app',
components: {
'my-component': MyComponent
}
});
Vue.js 利用双向数据绑定,将数据模型与视图模型连接起来。
利用双大年夜括号{{ }}
停止数据绑定。
<div>{{ message }}</div>
利用v-bind
指令停止属性绑定。
<div v-bind:title="title">Hello Vue!</div>
利用v-on
指令停止变乱绑定。
<button v-on:click="sayHello">Click me!</button>
打算属性基于它们的依附停止缓存,只有在相干依附产生改变时才会重新打算。
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
侦听器容许开辟者履行异步操纵。
watch: {
message(newVal, oldVal) {
console.log(`Message changed from ${oldVal} to ${newVal}`);
}
}
src/
|-- components/
| |-- TodoList.vue
| |-- TodoItem.vue
|-- App.vue
|-- main.js
<template>
<div>
<input v-model="newTodo" @keyup.enter="addTodo" placeholder="Add a todo">
<ul>
<todo-item
v-for="(todo, index) in todos"
:key="todo.id"
:todo="todo"
@remove-todo="removeTodo(index)"
></todo-item>
</ul>
</div>
</template>
<script>
import TodoItem from './TodoItem.vue';
export default {
components: {
TodoItem
},
data() {
return {
newTodo: '',
todos: []
};
},
methods: {
addTodo() {
const todo = {
id: this.todos.length,
content: this.newTodo,
completed: false
};
this.todos.push(todo);
this.newTodo = '';
},
removeTodo(index) {
this.todos.splice(index, 1);
}
}
};
</script>
<template>
<div>
<span :class="{ completed: todo.completed }">{{ todo.content }}</span>
<button @click="$emit('remove-todo', index)">Remove</button>
</div>
</template>
<script>
export default {
props: {
todo: Object,
index: Number
}
};
</script>
<style scoped>
.completed {
text-decoration: line-through;
}
</style>
src/
|-- components/
| |-- Weather.vue
|-- App.vue
|-- main.js
<template>
<div>
<input v-model="city" placeholder="Enter city name" @keyup.enter="fetchWeather">
<div v-if="weather">
<h1>Weather in {{ weather.name }}</h1>
<p>Temperature: {{ weather.main.temp }}°C</p>
<p>Weather: {{ weather.weather[0].description }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
city: '',
weather: null
};
},
methods: {
fetchWeather() {
const apiKey = 'YOUR_API_KEY';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
this.weather = data;
})
.catch(error => {
console.error('Error fetching weather:', error);
});
}
}
};
</script>
经由过程本文的进修,你曾经控制了Vue.js的基本知识跟实战技能。经由过程以上案例,你可能进一步懂得Vue.js的组件化开辟、数据绑定、打算属性、侦听器等核心不雅点。在现实项目中,一直现实跟积聚经验,你将可能更好地应用Vue.js构建富强的用户界面。