如何使用 Vue.js 创建一个简单的 Notes 应用程序

586 阅读4分钟

这是我参与8月更文挑战的第5天,活动详情查看: 8月更文挑战

Vue.js 不仅是一个 JavaScript 框架,它为 Web 开发带来了全新的概念,而且还推动了我们实现和交付应用程序的方式。Web 是一个不断变化的环境,需要支持创新的框架和技术。我们将开发一个简单但完整的笔记应用程序,以展示 Vue.js 的功能。

配置

为了使用 Vue.js 创建项目,您需要在您的计算机上安装 Node.js 和 npm。完成后,只需在终端中键入以下命令:

npm install --global vue-cli

这足以将 Vue.js 的主要模块作为全局 npm 包分发给您操作系统的所有用户。接下来,让我们通过以下命令创建一个新的应用程序:

vue init webpack notes-app

然后会提示您填写一些项目信息。见下文:

设置完成后,让我们跳转到项目的根文件夹并运行命令:

npm install

这是必要的,因为我们必须下载项目所需的所有依赖项。之后,让应用程序正常运行的唯一方法就是执行以下命令:

npm run dev

这将在本地启动服务器并 在本地浏览器上打开http://localhost:8080的默认应用程序模板。

接下来,让我们直接进入我们的项目结构并进入根文件/index.html。粘贴以下代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Notes App</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.css">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

这就是我们在主页上导入 jQuery 和 Semantic.js 库所需的全部内容。它们是使元素选择以及某些内置组件的样式所必需的。然后,打开文件App.vue 并将其内容替换为以下内容:

<template>
  <div id="app">
    <h1 class="ui centered header">Vue.js Notes App</h1>
    <div>
      <list-notes v-bind:notes="notes"></list-notes>
      <create-note v-on:create-note="createNote"></create-note>
    </div>
  </div>
</template>

<script>
  import ListNotes from './components/ListNotes';
  import CreateNote from './components/CreateNotes';
  export default {
    name: 'app',
    components: {
      ListNotes,
      CreateNote,
    },
    data() {
      return {
        notes: [{
          title: 'Lunch at 12PM',
          description: 'Call Robert to remember him.'
        }, {
          title: 'Gym with Jane',
          description: 'She is needing your motivation...'
        }, {
          title: 'Call mom',
          description: 'Ask her about the cats?'
        }],
      };
    },
    methods: {
      createNote(note) {
        this.notes.push(note);
        alert('Note created!');
      },
    },
  };
</script>

配置主模板

在这里,我们正在配置主页的主模板,以及用于启用页面按钮主要操作的 JavaScript — 创建和列出我们的笔记。第一行涵盖了 Vue.js 识别的模板系统,用于将每个标签定义为一个组件(在本例中为<list-notes> 和<create-note>)。该v-bind 属性将其值连接到 data() 函数,该函数提供与每个字段相关联的原始值。与 相同v-on,它反过来负责事件关联。

其余代码简单地导入我们将创建的模块,定义此应用程序的名称以及将管理它们的功能。现在让我们跳到我们的新 Vue 文件:CreateNotes.vue,您必须在项目中从头开始创建。看一下代码:

<template>
  <div class='ui basic content center aligned segment'>
    <button class='ui basic button icon' v-on:click="openForm" v-show="!isCreating">
      <i class='plus icon'></i>
    </button>
    <div class='ui centered card' v-show="isCreating">
      <div class='content'>
        <div class='ui form'>
          <div class='field'>
            <label>Title</label>
            <input v-model="titleText" type='text'>
          </div>
          <div class='field'>
            <label>Description</label>
            <input v-model="descriptionText" type='text'>
          </div>
          <div class='ui two buttons'>
            <button class='ui basic green button' v-on:click="sendForm()">
              Create
            </button>
            <button class='ui basic black button' v-on:click="closeForm">
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      titleText: '',
      descriptionText: '',
      isCreating: false,
    };
  },
  methods: {
    openForm() {
      this.isCreating = true;
    },
    closeForm() {
      this.isCreating = false;
    },
    sendForm() {
      if (this.titleText.length > 0 && this.descriptionText.length > 0) {
        const title = this.titleText;
        const description = this.descriptionText;
        this.$emit('create-note', {
          title,
          description,
        });
        // Clean fields after submit
        this.titleText = '';
        this.descriptionText = '';
        this.isCreating = false;
      }
    },
  },
};
</script>

这个稍微复杂一点。除了我们已经看到的关于 Vue.js 及其模板关联的所有其他内容之外,我们基本上有每个笔记创建的表单模板:一个按钮(带有“加号”图标)打开真实表单,表单本身包含提交/取消操作的字段和按钮。请注意,属性 v-show 对于设置是否显示整个 div 很重要。并且v-model 封装了我们之前见过的音符表示的模型对象。

下面,我们有将打开/关闭表单的 JavaScript 数据和函数(通过我们实现的属性“isCreating”),以及将传播笔记创建的函数。

为了完成这项工作,我们需要一个新Note.vue 文件(进入/components 文件夹)来代表屏幕上的每个音符。我们来看看这个内容:

<template>
  <div class='ui centered card'>
    <div class="content" v-show="!showEditForm">
      <div class='header'>
          {{ note.title }}
      </div>
      <div class='meta italic'>
          {{ note.description }}
      </div>
      <div class='extra content'>
          <span class='right floated edit icon' v-on:click="showForm">
          <i class='edit icon'></i>
        </span>
        <span class='right floated trash icon' v-on:click="deleteNote(note)">
          <i class='trash icon'></i>
        </span>
      </div>
    </div>
    <div class="content" v-show="showEditForm">
      <div class='ui form'>
        <div class='field'>
          <label>Title</label>
          <input type='text' v-model="note.title" >
        </div>
        <div class='field'>
          <label>Description</label>
          <input type='text' v-model="note.description" >
        </div>
        <div class='ui two buttons'>
          <button class='ui basic button' v-on:click="hideForm">
            Close X
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">
  export default {
    props: ['note'],
    data() {
      return {
        showEditForm: false,
      };
    },
    methods: {
      deleteNote(note) {
        this.$emit('delete-note', note);
      },
      showForm() {
        this.showEditForm = true;
      },
      hideForm() {
        this.showEditForm = false;
      },
    },
  };
</script>

<style scoped>
  .italic {font-style: italic}
</style>

看到我们正在使用 SemanticUI 中的卡片元素使它们更漂亮和干净。卡片的每个值都通过 Vue.js 的方括号样式来表示来打印 things {{}},这是它的语法非常有特色的东西。我们还有两个字段必须填充以前的值,以及一个关闭按钮。删除事件将发生在我们的下一个文件上:ListNotes.vue,让我们看看它的内容:

<template>
  <div>
    <note v-on:delete-note="deleteNote" v-for="note in notes" :note.sync="note"></note>
  </div>
</template>

<script type = "text/javascript" >
  import Note from './Note';
  export default {
    props: ['notes'],
    components: {
      Note
    },
    methods: {
      deleteNote(note) {
        var removeIt = confirm('Do you really wanna remove it?');
        if (removeIt) {
          const noteIndex = this.notes.indexOf(note);
          this.notes.splice(noteIndex, 1);
          alert('Note deleted!');
        }
      },
    },
  };
</script>

这个模板的第一个标签设置了一个事件侦听器“delete-note”并分配给函数deleteNote (相应的代码如下所列)。在这里,我们使用了另外两个属性:

  • v-for:这个对于迭代我们从模型对象中捕获的笔记列表很重要。这种操作非常有用,Vue.js 提供了一个完整的解决方案来处理它

  • :note-sync : 在这里,我们对 Vue.js 说它需要重新加载我们的整个笔记 模型,以便通知发生了重要的变化

    而已。您可以重新运行您的项目并查看最终结果。作为提示,我建议您删除 ESLint 验证,因为当您第一次尝试运行此代码时,它们会导致很多编译错误。否则,您可以查看指出的每个错误/警告并修复它们。查看您必须在文件中删除的拉伸bin/webpack.base.conf.js

    {
        test: /.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter')
        }
    },
    

    在下面,您可以看到我们最终运行的应用程序的一些屏幕截图。

    结论

    Vue.js 是一个非常快速和简单的框架,它允许在我们的 Web 应用程序中进行各种配置,使它们更易于使用和维护。现在,轮到您自定义笔记应用程序了。尝试添加更多功能,让人们使用起来更有趣。祝你好运!