Vue 3 内置属性语法知识点及案例代码
Vue 3 提供了丰富的内置属性,帮助开发者高效地构建用户界面。以下将详细介绍 Vue 3 的主要内置属性,并结合详细的案例代码进行说明。每个案例代码都包含详细的注释,帮助初学者更好地理解其用法。
1. data
知识点
data
: 用于定义组件的响应式数据。- 在 Vue 3 中,
data
必须是一个返回对象的函数。 - 响应式数据的变化会自动更新视图。
案例代码
<template>
<div>
<h1>{{ message }}</h1>
<button @click="updateMessage">更新消息</button>
</div>
</template>
<script>
export default {
name: 'DataExample',
data() {
return {
message: 'Hello, Vue 3!'
};
},
methods: {
updateMessage() {
this.message = '消息已更新!';
}
}
};
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
说明:
data
函数返回一个包含message
属性的对象。- 点击按钮时,
updateMessage
方法会更新message
的值,视图会自动刷新。
2. methods
知识点
methods
: 用于定义组件中的方法。- 方法中的
this
指向当前组件实例,可以访问data
、props
等属性。
案例代码
<template>
<div>
<p>计数器: {{ count }}</p>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
</div>
</template>
<script>
export default {
name: 'MethodsExample',
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
},
decrement() {
this.count--;
}
}
};
</script>
<style scoped>
button {
margin: 0 5px;
}
</style>
说明:
- 定义了两个方法
increment
和decrement
,用于增加和减少count
的值。 - 按钮点击时调用相应方法,更新视图。
3. computed
知识点
computed
: 用于定义计算属性,基于依赖进行缓存。- 计算属性只有在依赖发生变化时才会重新计算。
- 适用于需要基于现有数据计算出新数据的场景。
案例代码
<template>
<div>
<p>原始价格: {{ price }} 元</p>
<p>折扣价格: {{ discountedPrice }} 元</p>
<button @click="increasePrice">增加价格</button>
</div>
</template>
<script>
export default {
name: 'ComputedExample',
data() {
return {
price: 100
};
},
computed: {
discountedPrice() {
return this.price * 0.9; // 假设打9折
}
},
methods: {
increasePrice() {
this.price += 10;
}
}
};
</script>
<style scoped>
button {
margin-top: 10px;
}
</style>
说明:
discountedPrice
是一个计算属性,基于price
计算折扣后的价格。- 当
price
变化时,discountedPrice
会自动更新。
4. watch
知识点
watch
: 用于监听数据的变化,并在变化时执行相应的回调函数。- 适用于需要在数据变化时执行异步操作或复杂逻辑的场景。
案例代码
<template>
<div>
<p>用户名: {{ username }}</p>
<input v-model="username" placeholder="输入用户名" />
<p v-if="isUsernameValid">用户名有效</p>
<p v-else>用户名无效</p>
</div>
</template>
<script>
export default {
name: 'WatchExample',
data() {
return {
username: '',
isUsernameValid: false
};
},
watch: {
username(newVal) {
if (newVal.length >= 3) {
this.isUsernameValid = true;
} else {
this.isUsernameValid = false;
}
}
}
};
</script>
<style scoped>
input {
margin-top: 10px;
padding: 5px;
}
</style>
说明:
watch
监听username
的变化。- 根据
username
的长度更新isUsernameValid
的值。 - 输入框内容变化时,视图会根据
isUsernameValid
显示相应的提示。
5. props
知识点
props
: 用于接收父组件传递的数据。- 可以是数组或对象,用于定义组件的接收属性。
案例代码
父组件
<template>
<div>
<ChildComponent :greeting="message" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
data() {
return {
message: '你好,Vue 3!'
};
}
};
</script>
子组件 (ChildComponent.vue
)
<template>
<div>
<h2>{{ greeting }}</h2>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
greeting: {
type: String,
required: true
}
}
};
</script>
<style scoped>
h2 {
color: #35495e;
}
</style>
说明:
- 父组件通过
props
向子组件传递greeting
数据。 - 子组件通过
props
接收并使用该数据。
6. emit
知识点
emit
: 用于触发自定义事件,向父组件传递数据或通知事件。- 子组件通过
emit
触发事件,父组件监听并处理事件。
案例代码
子组件 (ChildComponent.vue
)
<template>
<div>
<button @click="notifyParent">通知父组件</button>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
methods: {
notifyParent() {
this.$emit('child-event', '来自子组件的消息');
}
}
};
</script>
<style scoped>
button {
padding: 5px 10px;
}
</style>
父组件
<template>
<div>
<h1>{{ message }}</h1>
<ChildComponent @child-event="handleChildEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
data() {
return {
message: '等待子组件的消息...'
};
},
methods: {
handleChildEvent(payload) {
this.message = payload;
}
}
};
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
说明:
- 子组件通过
this.$emit
触发child-event
事件,并传递一个字符串作为负载。 - 父组件监听
child-event
事件,并调用handleChildEvent
方法处理事件。 - 父组件的
message
会根据子组件传递的负载进行更新。
7. v-model
知识点
v-model
: 用于在表单输入元素和组件状态之间创建双向绑定。- 简化了表单处理和数据绑定。
案例代码
<template>
<div>
<input v-model="text" placeholder="输入文本" />
<p>输入的内容: {{ text }}</p>
</div>
</template>
<script>
export default {
name: 'VModelExample',
data() {
return {
text: ''
};
}
};
</script>
<style scoped>
input {
padding: 5px;
margin-bottom: 10px;
}
</style>
说明:
v-model
双向绑定text
数据和输入框的值。- 输入框内容变化时,
text
的值会实时更新,反之亦然。
8. v-bind
和 v-on
知识点
v-bind
: 用于动态绑定 HTML 属性或组件的props
。v-on
: 用于绑定事件监听器。
案例代码
<template>
<div>
<img v-bind:src="imageUrl" alt="示例图片" />
<button v-on:click="changeImage">更换图片</button>
</div>
</template>
<script>
export default {
name: 'VBindVOnExample',
data() {
return {
imageUrl: 'https://via.placeholder.com/150',
images: [
'https://via.placeholder.com/150',
'https://via.placeholder.com/200',
'https://via.placeholder.com/250'
]
};
},
methods: {
changeImage() {
const index = Math.floor(Math.random() * this.images.length);
this.imageUrl = this.images[index];
}
}
};
</script>
<style scoped>
img {
width: 150px;
height: 150px;
margin-bottom: 10px;
}
button {
padding: 5px 10px;
}
</style>
说明:
v-bind:src
动态绑定图片的src
属性。v-on:click
绑定点击事件,调用changeImage
方法更换图片。- 点击按钮时,随机选择一张图片并更新
imageUrl
,图片会实时更换。
9. v-if
和 v-for
知识点
v-if
: 根据条件渲染元素。v-for
: 用于遍历数组或对象,渲染列表。
案例代码
<template>
<div>
<h2>水果列表</h2>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{{ index + 1 }}. {{ fruit.name }}
<button v-if="fruit.quantity > 0" @click="buyFruit(index)">购买</button>
<span v-else>已售罄</span>
</li>
</ul>
<p>总购买数量: {{ totalPurchased }}</p>
</div>
</template>
<script>
export default {
name: 'VIfVForExample',
data() {
return {
fruits: [
{ name: '苹果', quantity: 5 },
{ name: '香蕉', quantity: 0 },
{ name: '橘子', quantity: 3 }
],
totalPurchased: 0
};
},
methods: {
buyFruit(index) {
if (this.fruits[index].quantity > 0) {
this.fruits[index].quantity--;
this.totalPurchased++;
}
}
}
};
</script>
<style scoped>
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 5px 0;
}
button {
margin-left: 10px;
padding: 2px 5px;
}
</style>
说明:
- 使用
v-for
遍历fruits
数组,渲染水果列表。 - 使用
v-if
判断水果的quantity
是否大于 0,显示“购买”按钮或“已售罄”。 - 点击“购买”按钮时,减少对应水果的数量,并增加总购买数量。
10. provide
和 inject
知识点
provide
: 用于向子组件提供数据或方法。inject
: 用于在子组件中接收provide
提供的数据或方法。
案例代码
祖先组件 (AncestorComponent.vue
)
<template>
<div>
<h1>祖先组件</h1>
<ChildComponent />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'AncestorComponent',
components: {
ChildComponent
},
provide() {
return {
ancestorMessage: '来自祖先组件的消息'
};
}
};
</script>
子组件 (ChildComponent.vue
)
<template>
<div>
<h2>子组件</h2>
<p>{{ ancestorMessage }}</p>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
inject: ['ancestorMessage']
};
</script>
<style scoped>
h2 {
color: #35495e;
}
</style>
说明:
- 祖先组件通过
provide
提供ancestorMessage
数据。 - 子组件通过
inject
接收ancestorMessage
,并在模板中使用。 - 这种方式可以实现跨层级组件间的数据共享。
总结
以上介绍了 Vue 3 中常用的内置属性及其用法,包括 data
、methods
、computed
、watch
、props
、emit
、v-model
、v-bind
、v-on
、v-if
、v-for
、provide
和 inject
。每个知识点都配有详细的案例代码和注释,帮助初学者更好地理解和应用这些属性。
通过不断实践和深入学习,您将能够熟练地使用这些属性,构建功能丰富、响应式的 Vue 3 应用。