Vue 2 组件创建全指南:一步一步学习

文章目录

  • [步骤 1: 创建组件文件](#步骤 1: 创建组件文件)
      • [步骤 2: 定义模板](#步骤 2: 定义模板)
      • [步骤 3: 添加脚本](#步骤 3: 添加脚本)
      • [步骤 4: 添加样式](#步骤 4: 添加样式)
      • [步骤 5: 使用组件](#步骤 5: 使用组件)

步骤 1: 创建组件文件

通常,一个 Vue 组件被创建为一个单文件组件 (Single File Component),这意味着它的模板、脚本和样式都包含在一个 .vue​ 文件中。首先,创建一个新的 .vue​ 文件,比如 MyComponent.vue​。

步骤 2: 定义模板

组件的模板定义了 HTML 结构,并可以使用 Vue 的指令进行数据绑定和交互。模板部分位于 <template>​ 标签内。

MyComponent.vue

vue 复制代码
<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="updateMessage">点击我</button>
  </div>
</template>

步骤 3: 添加脚本

<script>​ 标签中,你可以定义组件的状态(数据)、方法、生命周期钩子等。这里是组件的逻辑部分。

vue 复制代码
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    };
  },
  methods: {
    updateMessage() {
      this.message = '你好,Vue 2!';
    }
  }
}
</script>

步骤 4: 添加样式

组件的样式可以在 <style>​ 标签中定义。你可以选择使样式局部有效(默认行为,通过添加 scoped​ 属性)或全局有效。

vue 复制代码
<style scoped>
h1 {
  color: blue;
}
button {
  background-color: green;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}
</style>

步骤 5: 使用组件

为了在 Vue 应用中使用这个组件,你需要在父组件中导入并注册它。例如,如果你想在 App.vue​ 组件中使用 MyComponent​,可以这样做:

vue 复制代码
<template>
  <div id="app">
    <my-component></my-component>
  </div>
</template>

<script>
import MyComponent from './components/MyComponent.vue';

export default {
  name: 'App',
  components: {
    MyComponent
  }
}
</script>

相关推荐
whyfail1 小时前
Vue原理(暴力版)
前端·vue.js
踢球的打工仔1 小时前
jquery的基本使用(3)
前端·javascript·jquery
徐同保2 小时前
js 点击按钮 把文本转成文件并下载下来
开发语言·javascript·ecmascript
VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue敬老院管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
bug总结2 小时前
前端开发中为什么要使用 URL().origin 提取接口根地址
开发语言·前端·javascript·vue.js·html
程序员爱钓鱼3 小时前
Node.js 编程实战:数据库连接池与性能优化
javascript·后端·node.js
老华带你飞3 小时前
建筑材料管理|基于springboot 建筑材料管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
Gomiko3 小时前
JavaScript DOM 原生部分(二):元素内容修改
开发语言·javascript·ecmascript
一招定胜负3 小时前
网络爬虫(第三部)
前端·javascript·爬虫
Data_agent4 小时前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript