【Vue】单文件的组件(.vue)代码实例

注1:单文件.vue必须在脚手架环境下才能

注2:各组件中防止.class名称重复:<style scoped></style>

1、Student.vue

<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>

2、School.vue

<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>

3、App.vue(引用School.vue和Student.vue组件)

<template>
  <div class="app">

  </div>
</template>

<script>
// 引入组件
import School from "./School.vue";
import Student from "./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、main.js(执行入口)

import App from './App.vue'
new Vue({
    el: '#box',
    template:`<App></App>`,
    component: {
        App
    }
})

以上环境只能在脚手架环境下运行

猜你喜欢

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