【Vue】Vue-cli(脚手架)实现单文件Vue组件的调用(图文和代码)

一、实现效果

 二、实现步骤

1、单文件Vue组件School.Vue(在components)

<template>
  <!-- 组件一 -->
  <div class="demo">
    <h2>---------【School.vue】---------</h2>
    <h2>学校名称:{
   
   { schoolName }}</h2>
    <h2>学校地址:{
   
   { address }}</h2>
    <button @click="showName">点我提示学校</button>
  </div>
</template>

<script>
// 把组件暴露出去,方便引入  Vue.extend可以省略
export default {
  name:"School",
  date() {
    return {
      schoolName: "清华大学",
      address: "北京",
    };
  },
  methods: {
    showName() {
      alert(this.schoolName);
    },
  },
};
</script>

<style>
.demo {
  background-color: antiquewhite;
  border: 1px red solid;
}
</style>

2、单文件Vue组件Student.Vue(在components)

<template>
  <!-- 组件一 -->
  <div class="demo">
    <h2>---------【Student.vue】---------</h2>
    <h2>入取该校第1名学生:{
   
   { name1 }}</h2>
    <h2>入取该校第2名学生:{
   
   { name2 }}</h2>
    <h2>入取该校第3名学生:{
   
   { name3 }}</h2>
    <button @click="showName">点我提示第一名学生</button>
  </div>
</template>

<script>
// 把组件暴露出去,方便引入  Vue.extend可以省略
export default {
  name:"Student",
  date() {
    return {
      name1: "孔明",
      name2: "司马懿",
      name3:"曹操"
    };
  },
  methods: {
    showName() {
      alert(this.name1);
    },
  },
};
</script>

<style>
.demo {
  background-color: rgb(231, 231, 231);
  border: 1px rgb(172, 172, 172) solid;
}
</style>

3、单文件Vue组件App.Vue

<template>
  <div>
    <img src="./assets/logo.png" style="width:130px;height:130px">
    <School></School>
    <Student></Student>


  </div>
</template>

<script>
// 引入组件
import School from './components/School.vue'
import Student from './components/Student.vue'
// 注册组件
export default {
  name: "App",
  components: {
    School,
    Student
  },
};
</script>

<style>
.app {
  background-color: rgb(0, 0, 0);
  border: 1px rgb(255, 255, 255) solid;
  height: 300px;
  width: 500px;
}
</style>

4、注意:以上三个文件放在脚手架的位置

  5、main.js

// 引入Vue
import Vue from 'vue'
// 引入app组件,它是所有组件的父组件
import App from './App.vue'
// 关闭vue生产提示
Vue.config.productionTip = false

// 创建vue实例对象 -- vm

new Vue({
  el:"#app",
  // 完成了这个功能:将APP组件放入窗口中
  render: h => h(App),
})

6.index.html (http://localhost:8080的启动页)

注意:

1.调用public文件夹下的文件,使用:<%= BASE_URL %>

2.<%= htmlWebpackPlugin.options.title %>中的内容,是从【package.json】中获取的

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/dxnn520/article/details/123787206