Vue组件基础操作介绍

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue组件基础操作介绍

鸣鲷有柒   2023-02-03 我要评论

一、组件

组件是vue的重要的特征之一,可以扩展html的功能,也可以封装代码实现重复使用。

二、组件的创建

1. 非脚手架方式下创建

​ 第一步:使用Vue.extend创建组件

​ 第二步:使用Vue.component注册组件

​ 第三步:在html页面中使用组件

 <div id="app">
        <my-com></my-com>  <!-- 使用组件:名称之间用'-'连接  -->
    </div>
    <script>
        //第一步:使用Vue.extend创建组件
        var mycom = Vue.extend({
            template:'<h2>白桦林</h2>'   //template:指定页面中要展示的html结构
        })
        //第二步:使用Vue.component注册组件
        Vue.component('myCom',mycom)  //'myCom'是注册的组件名,在注册时采用驼峰命名
        new Vue({
            el:'#app'
        })
    </script>

2. 使用template创建组件

​ 第一步:使用template创建html页面模板,并给template定义id属性

​ 第二步:使用template的id属性值进行注册

强调:在Vue实例外部通过Vue.component创建或注册的组件称为全局组件

局部组件:创建方式和全局组件的创建方式一样,注册时必须放在Vue实例内部通过components完成

3. 在WebStorm中使用脚手架创建组件:

创建Vue component,组件命名采用驼峰命名法

  <template>
      //必须有一个html的标签作为模板的根标签
  </template>

三、组件中的data

1. 每个组件都有自己的数据:即每个组件都有自己的data

2. vue实例的data和组件的data的区别

​ 1)vue实例的data是一个对象

​ 2)组件的data必须是一个方法,该方法必须返回一个对象

3)vue实例中的data和组件中data在使用方法上是一样的

四、组件中的methods

组件中的methods和vue实例中的methods用法相同

练习:定义一个Vue组件,组件的名称是StudentInfo,在该组件中显示3条学生信息(编号、姓名、性别、地址)

<template>
<div>
  <table border="1" align="center">
    <thead>
    <tr>
      <th width="100">编号</th>
      <th width="100">姓名</th>
      <th width="100">年龄</th>
      <th width="100">性别</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(info,index) in info" :key="index">
      <td>{{ info.id}}</td>
      <td>{{ info.name}}</td>
      <td>{{ info.age}}</td>
      <td>{{ info.sex}}</td>
    </tr>
    </tbody>
  </table>
</div>
</template>
<script>
export default {
  name: "StudentInfo",
  data(){
    return {
      info:[
        {id:1001,name:'黄忠',age:44,sex:'男'},
        {id:1001,name:'小乔',age:19,sex:'女'},
        {id:1001,name:'周瑜',age:22,sex:'男'},
        {id:1001,name:'刘备',age:34,sex:'男'},
      ]
    }
  }
}
</script>
<style scoped>
</style>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们