当前位置:首页 > VUE

vue模版实现

2026-01-13 06:07:55VUE

以下是Vue模板实现的常见方法和示例,分为基础语法、数据绑定、条件渲染、列表渲染等部分:

基础模板结构

Vue单文件组件(.vue)通常包含<template><script><style>三个部分:

<template>
  <div id="app">
    {{ message }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

<style scoped>
#app {
  font-size: 16px;
}
</style>

数据绑定

使用双大括号插值或v-bind指令:

<template>
  <div>
    <p>{{ dynamicText }}</p>
    <a v-bind:href="url">Link</a>
    <!-- 简写 -->
    <a :href="url">Shortcut</a>
  </div>
</template>

条件渲染

v-if和v-show控制元素显示:

vue模版实现

<template>
  <div>
    <p v-if="isVisible">显示内容</p>
    <p v-else>备选内容</p>
    <span v-show="hasError">错误提示</span>
  </div>
</template>

列表渲染

v-for渲染数组或对象:

<template>
  <ul>
    <li v-for="(item, index) in items" :key="item.id">
      {{ index }} - {{ item.name }}
    </li>
  </ul>
</template>

事件处理

v-on监听DOM事件:

<template>
  <button v-on:click="handleClick">Click</button>
  <!-- 简写 -->
  <button @click="handleClick">Shortcut</button>
</template>

表单输入绑定

v-model实现双向绑定:

vue模版实现

<template>
  <input v-model="inputText" placeholder="Edit me">
  <p>Message is: {{ inputText }}</p>
</template>

插槽使用

父组件传递模板片段:

<!-- 子组件 -->
<template>
  <div class="container">
    <slot name="header"></slot>
    <slot></slot>
  </div>
</template>

<!-- 父组件 -->
<template>
  <ChildComponent>
    <template v-slot:header>
      <h1>标题</h1>
    </template>
    <p>默认插槽内容</p>
  </ChildComponent>
</template>

动态组件

通过is属性切换组件:

<template>
  <component :is="currentComponent"></component>
</template>

自定义指令

注册并使用自定义指令:

<template>
  <p v-highlight="'yellow'">高亮文本</p>
</template>

<script>
export default {
  directives: {
    highlight(el, binding) {
      el.style.backgroundColor = binding.value
    }
  }
}
</script>

这些示例覆盖了Vue模板的核心功能,实际开发中可根据需求组合使用这些特性。注意模板中避免使用纯JavaScript表达式,复杂逻辑应移至计算属性或方法中处理。

标签: 模版vue
分享给朋友:

相关文章

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

vue 实现关闭

vue 实现关闭

Vue 实现关闭功能的方法 在Vue中实现关闭功能通常涉及组件销毁、模态框隐藏或路由跳转等场景。以下是几种常见实现方式: 销毁当前组件 使用v-if或v-show控制组件显示/隐藏,适用于局部组件:…

vue实现类别

vue实现类别

Vue 实现类别的几种方法 在 Vue 中实现类别功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-bind:class 动态绑定类名 通过对象语法或数组语法动态绑定类名,根据条件添加或移…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue2…

vue实现录音

vue实现录音

Vue 实现录音功能 在 Vue 中实现录音功能可以通过浏览器提供的 MediaRecorder API 完成。以下是具体实现方法: 引入依赖 确保项目支持现代浏览器 API,无需额外安装库。若需兼…

vue实现tip

vue实现tip

Vue实现Tooltip的方法 使用Vue实现Tooltip可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML的title属性 在Vue模板中直接使用HTML的title属性是最简单的实…