Vue学习之--------组件在Vue脚手架中的使用(代码实现)(2022/7/24)

1、第一步编写组件

  • template中进行页面结构(必须要有一个根节点(div))
  • script 中进行数据的交互操作、data、method、watch…
  • style 进行页面样式设计
    注意 :需要向外抛出组件

1.1 编写一个 展示学校的组件

<template>
  <div class="demo">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
    <button @click="showName">点我提示学校名</button>
  </div>
</template>

<script>
export default {
  name: "School",
  data() {
    return {
      name: "长沙大学",
      address: "湖南长沙",
    };
  },
  methods: {
    showName() {
      alert(this.name);
    },
  },
};
</script>

<style>
.demo {
  background-color: pink;
}
</style>

1.2 定义一个展示学生的信息组件

<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				name:'张三',
				age:18
			}
		}
	}
</script>

2、第二步引入组件

  • 1、引入组件
  • 2、注册组件
  • 3、在指定位置使用
<template>
	<div>
		<School></School>
		<Student></Student>
	</div>
</template>

<script>
	//引入组件
	import School from './School.vue'
	import Student from './Student.vue'

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


3、制作一个容器

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>myvue</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

4、使用Vue接管 容器

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

5、实际效果

在这里插入图片描述

6、友情提示:

需要使用Vue脚手架

7、项目的目录结构

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

posted on 2022-08-28 22:16  热爱技术的小郑  阅读(1)  评论(0编辑  收藏  举报