当前位置:首页 > VUE

vue实现的例子

2026-02-18 00:17:22VUE

以下是几个基于 Vue.js 实现的典型示例,涵盖不同场景和技术要点:

基础计数器组件

<template>
  <div>
    <button @click="decrement">-</button>
    <span>{{ count }}</span>
    <button @click="increment">+</button>
  </div>
</template>

<script>
export default {
  data() {
    return { count: 0 }
  },
  methods: {
    increment() { this.count++ },
    decrement() { this.count-- }
  }
}
</script>

表单双向绑定

<template>
  <div>
    <input v-model="message" placeholder="输入内容">
    <p>实时预览: {{ message }}</p>
  </div>
</template>

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

动态列表渲染

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

<script>
export default {
  data() {
    return {
      items: [
        { text: '项目1' },
        { text: '项目2' }
      ]
    }
  }
}
</script>

组件间通信(Props + Events)

父组件:

<template>
  <child-component 
    :title="parentTitle" 
    @update-title="handleUpdate"
  />
</template>

<script>
import ChildComponent from './Child.vue'
export default {
  components: { ChildComponent },
  data() {
    return { parentTitle: '初始标题' }
  },
  methods: {
    handleUpdate(newTitle) {
      this.parentTitle = newTitle
    }
  }
}
</script>

子组件:

<template>
  <div>
    <h2>{{ title }}</h2>
    <button @click="changeTitle">修改标题</button>
  </div>
</template>

<script>
export default {
  props: ['title'],
  methods: {
    changeTitle() {
      this.$emit('update-title', '新标题')
    }
  }
}
</script>

状态管理(Vuex)

Store 定义:

import Vuex from 'vuex'
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  }
})

组件中使用:

vue实现的例子

<template>
  <div>
    {{ $store.state.count }}
    <button @click="$store.commit('increment')">+1</button>
  </div>
</template>

这些示例覆盖了 Vue 的核心功能,包括数据绑定、组件化开发、状态管理等实际开发中的常见模式。

标签: 例子vue
分享给朋友:

相关文章

vue实现按钮组轮换

vue实现按钮组轮换

实现按钮组轮换的方法 在Vue中实现按钮组轮换效果可以通过动态绑定类和事件处理来完成。以下是一种常见的实现方式: 模板部分 <template> <div class="bu…

vue 实现级联

vue 实现级联

Vue 实现级联选择器 级联选择器(Cascader)常用于省市区选择、分类选择等场景。Vue 中可以通过 Element UI、Ant Design Vue 等 UI 库实现,也可以手动封装。 使…

vue实现图片

vue实现图片

Vue 实现图片功能的方法 静态图片引入 在 Vue 项目中,可以通过 src 属性直接引入静态图片。图片通常放在 public 或 assets 目录下。 <template> &…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…

vue实现横滚

vue实现横滚

Vue 实现横滚效果 横滚效果通常指水平滚动内容,常见于轮播图、横向导航栏等场景。以下是几种实现方式: 使用 CSS 和 Vue 结合 通过 CSS 的 overflow-x 和 white-spa…

vue实现画板

vue实现画板

Vue 实现画板功能 在 Vue 中实现画板功能可以通过 HTML5 的 Canvas API 实现。以下是一个完整的实现方案: 创建 Vue 组件 新建一个 Vue 单文件组件(SFC),命名为…