引言
Vue基础知识
在开始之前,确保您已经对 Vue 的基本概念有所了解,包括:
- Vue 实例
- 数据绑定
- 模板语法
- 计算属性和
如果您还不熟悉这些概念,建议先阅读 Vue 的官方文档或相关教程。
数据绑定
数据绑定是 Vue 的核心特性之一,它允许您将数据模型与视图紧密连接。以下是如何在 Vue 中实现数据绑定的基本步骤:
1. 创建 Vue 实例
new Vue({
  el: '#app',
  data: {
    message: 'Hello, Vue!'
  }
});
2. 使用插值表达式
在模板中使用双大括号 {{ }} 来显示数据:
<div id="app">
  <p>{{ message }}</p>
</div>
3. 更新数据
通过修改 Vue 实例的 data 对象来更新数据:
this.message = 'Hello, Vue! Updated';
组件评能
1. 创建评论组件
首先,创建一个名为 Comment.vue 的新文件:
<template>
  <div>
    <h3>Comments</h3>
    <ul>
      <li v-for="comment in comments" :key="comment.id">
        {{ comment.text }}
      </li>
    </ul>
    <form @submit.prevent="addComment">
      <input v-model="newComment" placeholder="Add a comment...">
      <button type="submit">Submit</button>
    </form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      comments: [],
      newComment: ''
    };
  },
  methods: {
    addComment() {
      if (this.newComment.trim() !== '') {
        this.comments.push({
          id: Date.now(),
          text: this.newComment
        });
        this.newComment = '';
      }
    }
  }
};
</script>
2. 在父组件中使用评论组件
在父组件中,引入并使用 Comment 组件:
<template>
  <div id="app">
    <Comment />
  </div>
</template>
<script>
import Comment from './Comment.vue';
export default {
  components: {
    Comment
  }
};
</script>
