三个小时vue3.x从零到实战(vue3.x经典案例46个)

简介: 该文章提供了46个Vue 3.x的经典案例,通过实际代码示例帮助开发者更好地理解和运用Vue 3.x的各项功能和技术。

注: 部分案例来源于官网。

1. 计数器从1到1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="counter">
  Counter: {
  { counter }}
</div>

<script>
  const Counter = {
    
    data() {
    
      return {
    
        counter: 0
      }
    },
    mounted() {
    
      setInterval(() => {
    
        this.counter++
      }, 1000)
    }
  }

Vue.createApp(Counter).mount('#counter')
</script>
</body>
</html>
2. 鼠标悬停几秒钟查看此处动态绑定的提示信息
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="bind-attribute">
  <span v-bind:title="message">
    鼠标悬停几秒钟查看此处动态绑定的提示信息!
  </span>
</div>

<script>
  const AttributeBinding = {
    
    data() {
    
      return {
    
        message: 'You loaded this page on ' + new Date().toLocaleString()
      }
    }
  }

  Vue.createApp(AttributeBinding).mount('#bind-attribute')
</script>
</body>
</html>
3. 翻转字符串
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="event-handling">
  <p>{
  { message }}</p>
  <button v-on:click="reverseMessage">反转 Message</button>
</div>

<script>
  const EventHandling = {
    
    data() {
    
      return {
    
        message: 'Hello Vue.js!'
      }
    },
    methods: {
    
      reverseMessage() {
    
        this.message = this.message
                .split('')
                .reverse()
                .join('')
      }
    }
  }

  Vue.createApp(EventHandling).mount('#event-handling')
</script>
</body>
</html>
4. 用户输入
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<!--表单数据输入和应用状态之间的双向数据绑定-->
<div id="two-way-binding">
  <p>{
  { message }}</p>
  <input v-model="message" />
</div>

<script>
  const TwoWayBinding = {
    
    data() {
    
      return {
    
        message: 'Hello Vue!'
      }
    }
  }

  Vue.createApp(TwoWayBinding).mount('#two-way-binding')
</script>
</body>
</html>
5. 控制元素是否显示
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="conditional-rendering">
<span v-if="seen">现在你看到我了</span>
</div>

<script>
  const ConditionalRendering = {
    
    data() {
    
      return {
    
        seen: true
      }
    }
  }

  Vue.createApp(ConditionalRendering).mount('#conditional-rendering')
</script>
</body>
</html>
6. 遍历数组
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="list-rendering">
  <ol>
    <li v-for="todo in todos">
      {
  { todo.text }}
    </li>
  </ol>
</div>

<script>
  const ListRendering = {
    
    data() {
    
      return {
    
        todos: [
          {
     text: 'Learn JavaScript' },
          {
     text: 'Learn Vue' },
          {
     text: 'Build something awesome' }
        ]
      }
    }
  }

  Vue.createApp(ListRendering).mount('#list-rendering')
</script>
</body>
</html>
7. 组件化应用构建
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="todo-list-app">
  <ol>
    <todo-item
            v-for="item in groceryList"
            v-bind:todo="item"
            v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>


<script>
  const TodoList = {
    
    data() {
    
      return {
    
        groceryList: [
          {
     id: 0, text: 'Vegetables' },
          {
     id: 1, text: 'Cheese' },
          {
     id: 2, text: 'Whatever else humans are supposed to eat' }
        ]
      }
    }
  }

  const app = Vue.createApp(TodoList)

  app.component('todo-item', {
    
    props: ['todo'],
    template: `<li>{
     { todo.text }}</li>`
  })

  app.mount('#todo-list-app')
</script>
</body>
</html>
8. 文本插值v-html的使用
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<style>
  .demo {
    
    font-family: sans-serif;
    border: 1px solid #eee;
    border-radius: 2px;
    padding: 20px 30px;
    margin-top: 1em;
    margin-bottom: 40px;
    user-select: none;
    overflow-x: auto;
  }
</style>

<body>
<div id="example1" class="demo">
  <p>Using mustaches: {
  { rawHtml }}</p>
  <p>Using v-html directive: <span v-html="rawHtml"></span></p>
</div>


<script>
  const RenderHtmlApp = {
    
    data() {
    
      return {
    
        rawHtml: '<span style="color: red">This should be red.</span>'
      }
    }
  }

  Vue.createApp(RenderHtmlApp).mount('#example1')
</script>
</body>
</html>
9. 计算属性的使用
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<style>
  .demo {
    
    font-family: sans-serif;
    border: 1px solid #eee;
    border-radius: 2px;
    padding: 20px 30px;
    margin-top: 1em;
    margin-bottom: 40px;
    user-select: none;
    overflow-x: auto;
  }
</style>

<body>
<div id="computed-basics" class="demo">
  <p>Has published books:</p>
  <span>{
  { publishedBooksMessage }}</span>
</div>


<script>
  Vue.createApp({
    
    data() {
    
      return {
    
        author: {
    
          name: 'John Doe',
          books: ['Vue 2 - Advanced Guide',
            'Vue 3 - Basic Guide',
            'Vue 4 - The Mystery']
        }
      }
    },
    computed: {
    
      // a computed getter
      publishedBooksMessage() {
    
        // `this` points to the vm instance
        return this.author.books.length > 0 ? 'Yes' : 'No'
      }
    }
  }).mount('#computed-basics')
</script>
</body>
</html>
10. 用watch回答以?结尾的问题
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
  <!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
  <!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
  <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>

<body>
<div id="watch-example">
  <p>
    输入一个问题,以 ? 号结尾输出答案:
    <input v-model="question" />
  </p>
  <p>{
  { answer }}</p>
</div>
<p id="info"></p>
<script>
  const watchExampleVM = Vue.createApp({
    
    data() {
    
      return {
    
        question: '',
        answer: '每个问题结尾需要输入英文的 ? 号。'
      }
    },
    watch: {
    
      // 每当问题改变时,此功能将运行,以 ? 号结尾
      question(newQuestion, oldQuestion) {
    
        if (newQuestion.indexOf('?') > -1) {
    
          this.getAnswer()
        }
      }
    },
    methods: {
    
      getAnswer() {
    
        this.answer = '加载中...'
        axios
                .get('https://yesno.wtf/api')
                .then(response => {
    
                  this.answer = response.data.answer
                })
                .catch(error => {
    
                  this.answer = '错误! 无法访问 API。 ' + error
                })
      }
    }
  }).mount('#watch-example')
</script>
</body>
</html>
11. 使用v-for遍历数组
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<ul id="array-rendering" class="demo">
  <li v-for="item in items" :key="item.message">
    {
  { item.message }}
  </li>

  <!-- 带索引 -->
  <li v-for="(item, index) in items">
    {
  { index }} - {
  { item.message }}
  </li>
</ul>

<script>
  Vue.createApp({
    
    data() {
    
      return {
    
        items: [{
     message: 'Foo' }, {
     message: 'Bar' }]
      }
    }
  }).mount('#array-rendering')
</script>
</body>
</html>
12. 使用v-for遍历对象
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<ul id="v-for-object" class="demo">
  <li v-for="value in myObject">
    {
  { value }}
  </li>

  <P>也可以提供第二个的参数为 property 名称 (也就是键名 key):</P>
  <li v-for="(value, name) in myObject">
    {
  { name }}: {
  { value }}
  </li>

  <P>还可以用第三个参数作为索引:</P>
  <li v-for="(value, name, index) in myObject">
    {
  { index }}. {
  { name }}: {
  { value }}
  </li>
</ul>

<script>
  Vue.createApp({
    
    data() {
    
      return {
    
        myObject: {
    
          title: 'How to do lists in Vue',
          author: 'Jane Doe',
          publishedAt: '2020-03-22'
        }
      }
    }
  }).mount('#v-for-object')
</script>
</body>
</html>
13. 在v-for里使用值的范围
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<div id="range" class="demo">
  <span v-for="n in 10">{
  { n }} </span>
</div>

<script>
  Vue.createApp({
    }).mount('#range')
</script>
</body>
</html>
14. 在组件上使用v-for
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<!--v-for 循环出列表,v-if 设置选中值:-->
<div id="todo-list-example">
  <form v-on:submit.prevent="addNewTodo">
    <label for="new-todo">添加 todo: </label>
    <input
            v-model="newTodoText"
            id="new-todo"
            placeholder="例如:明天早上跑步"
    />
    <button>添加</button>
  </form>
  <ul>
    <todo-item
            v-for="(todo, index) in todos"
            :key="todo.id"
            :title="todo.title"
            @remove="todos.splice(index, 1)"
    ></todo-item>
  </ul>
</div>


<!-- 在script里写vue代码 -->
<script>
  const app = Vue.createApp({
    
    data() {
    
      return {
    
        newTodoText: '',
        todos: [
          {
    
            id: 1,
            title: '看电影'
          },
          {
    
            id: 2,
            title: '吃饭'
          },
          {
    
            id: 3,
            title: '学习!!'
          }
        ],
        nextTodoId: 4
      }
    },
    methods: {
    
      addNewTodo() {
    
        this.todos.push({
    
          id: this.nextTodoId++,
          title: this.newTodoText
        })
        this.newTodoText = ''
      }
    }
  })

  app.component('todo-item', {
    
    template: `
    <li>
      {
     { title }}
      <button @click="$emit('remove')">删除</button>
    </li>
  `,
    props: ['title'],
    emits: ['remove']
  })

  app.mount('#todo-list-example')
</script>
</body>

</html>
15. 监听事件
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<div id="basic-event" class="demo">
  <button @click="counter += 1">Add 1</button>
  <p>The button above has been clicked {
  { counter }} times.</p>
</div>

<script>
  Vue.createApp({
    
    data() {
    
      return {
    
        counter: 0
      }
    }
  }).mount('#basic-event')
</script>
</body>

</html>
16. 事件处理方法
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue 测试实例</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<div id="basic-event" class="demo">
  <button @click="counter += 1">Add 1</button>
  <p>The button above has been clicked {
  { counter }} times.</p>
</div>

<script>
  Vue.createApp({
    
    data() {
    
      return {
    
        counter: 0
      }
    }
  }).mount('#basic-event')
</script>
</body>

</html>

为了减少篇幅,剩下30个可到:https://gitee.com/cuiyonghua/vue3.x-example

相关文章
|
1天前
|
缓存 JavaScript 前端开发
三个小时vue3.x从零到实战(vue3.x面试总结)
该文章总结了Vue 3.x面试中常见的知识点和问题,包括Vue的生命周期、核心概念、组件通信方式等方面的内容,有助于准备Vue相关技术面试。
8 0
|
1天前
|
存储 缓存 JavaScript
三个小时vue3.x从零到实战(前)(vue3.x基础)
该文章提供了关于Vue 3.x的基础教程,覆盖了从环境搭建到基本使用的各个方面,适合Vue 3.x的初学者。
7 0
|
1天前
|
JavaScript 前端开发 开发者
三个小时vue3.x从零到实战(中)(vue3.x高级语法)
该文章深入探讨了Vue 3.x的高级语法与特性,包括混入(mixins)的使用、组件间的通信方式等,帮助开发者掌握Vue 3.x的进阶知识。
9 0
|
1天前
|
JavaScript 开发者
三个小时vue3.x从零到实战(后)(vue3.x配套工具及项目化构建)
文章详细介绍了Vue 3.x相关的配套工具及项目化构建流程,包括构建工具的配置与最佳实践,帮助开发者更好地管理和构建Vue项目。
9 0
|
1天前
|
JavaScript 前端开发 编译器
三个小时vue3.x从零到实战(typescript的搭建、使用及资料)
该文章介绍了如何在Vue 3项目中集成TypeScript,包括TypeScript的安装、基本使用,以及如何通过TypeScript增强Vue应用程序的类型安全性。
9 0
|
JavaScript API 开发工具
【三十天精通 Vue 3】第二天 Vue 3带来的新特性
【三十天精通 Vue 3】第二天 Vue 3带来的新特性
129 2
|
存储 JavaScript 前端开发
【三十天精通 Vue 3】 第一天 Vue 3入门指南
【三十天精通 Vue 3】 第一天 Vue 3入门指南
248 1
|
存储 JSON JavaScript
【半小时入门vue】最容易理解的vue入门方式
【半小时入门vue】最容易理解的vue入门方式
|
缓存 JavaScript 前端开发
【三十天精通Vue 3】第二十天 Vue 3的性能优化详解
【三十天精通Vue 3】第二十天 Vue 3的性能优化详解
605 0
|
JavaScript 前端开发 API
想知道Vue3与Vue2的区别?五千字教程助你快速上手Vue3!(上)
想知道Vue3与Vue2的区别?五千字教程助你快速上手Vue3!(上)
263 0