Vue 指令详解:v-if、v-for、v-bind、v-on 等 10 个常用指令
Vue 指令详解:10 个常用指令
Vue.js 框架中,指令是用来扩展 HTML 的功能,使 HTML 可以与 Vue 响应式系统交互。下面介绍 10 个常用的指令:
- v-if: 根据表达式的真假条件来判断是否渲染元素。
<template>
<div v-if='show'>这是一个显示的元素</div>
</template>
<script>
export default {
data() {
return {
show: true
}
}
}
</script>
- v-for: 遍历数组或对象,生成相应的元素。
<template>
<ul>
<li v-for='(item, index) in items' :key='index'>{{ item }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['apple', 'banana', 'orange']
}
}
}
</script>
- v-bind: 绑定元素属性或组件 props 到表达式。
<template>
<img :src='imageUrl' alt='图片'>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://www.example.com/image.jpg'
}
}
}
</script>
- v-on: 绑定事件监听器到元素或组件。
<template>
<button v-on:click='handleClick'>点击我</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('按钮被点击了');
}
}
}
</script>
- v-model: 双向绑定表单元素和数据。
<template>
<input type='text' v-model='message'>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
}
}
}
</script>
- v-show: 根据表达式的真假条件来判断是否显示元素。
<template>
<div v-show='show'>这是一个显示的元素</div>
</template>
<script>
export default {
data() {
return {
show: true
}
}
}
</script>
- v-text: 更新元素的 textContent。
<template>
<p v-text='message'></p>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
}
}
}
</script>
- v-html: 更新元素的 innerHTML。
<template>
<div v-html='html'></div>
</template>
<script>
export default {
data() {
return {
html: '<h1>这是一个标题</h1>'
}
}
}
</script>
- v-cloak: 用于解决初始化渲染时闪烁问题。
<template>
<div v-cloak>内容</div>
</template>
<style>
[v-cloak] { display: none; }
</style>
- v-pre: 跳过元素和其子元素的编译过程。
<template>
<pre v-pre>{{ message }}</pre>
</template>
<script>
export default {
data() {
return {
message: '这是一个未被编译的文本'
}
}
}
</script>
通过以上介绍,你应该对 Vue 指令有了更深入的了解。在实际开发中,你需要根据具体情况选择合适的指令来实现你的需求。
希望这篇文章对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/joC0 著作权归作者所有。请勿转载和采集!