组件定义与使用
vue 文件的组成(3 个部分)
1) 模板页面
<template>
页面模板
</template>
2) JS 模块对象
<script>
export default {
data() {
return {}
},
methods: {},
computed: {},
components: {}
}
</script>
3) 样式
<style>
样式定义
</style>
基本使用
1) 引入组件
2) 映射成标签
3) 使用组件标签
<template>
<HelloWorld></HelloWorld>
<hello-world></hello-world>
</template>
<script>
import HelloWorld from './components/HelloWorld'
export default {
components: {
HelloWorld
}
}
</script>
关于标签名与标签属性名书写问题
1) 写法一: 一模一样
2) 写法二: 大写变小写, 并用-连接
实验
Hello_world.vue
<template>
<div>
<p class="msg">{{msg}}</p>
</div>
</template>
<script>
export default {
/*配置对象(与Vue一样)*/
/*必须写函数*/
data() {
return{
msg: 'Hello Vue Component'
}
}
}
</script>
<style>
.msg {
color: green;
background: #d7dad9;
}
</style>
App.vue
<template>
<div>
<img class="logo" src="./assets/logo.png" alt="logo">
<!--3 使用标签-->
<Hello_world/>
</div>
</template>
<script>
/*1 引入组件*/
import Hello_world from "./components/Hello_world";
export default {
/*2 映射组件标签*/
components: {
Hello_world
}
}
</script>
<style>
.logo{
width:200px;
height:200px;
}
</style>
main.js
/*
入口JS:创建Vue实例*/
import Vue from 'vue';
import App from './App.vue'
new Vue({
el:'#app',
components:{
App
},
template:'<App/>'
});