Vue 的组件的使用
在工程目录/src下components文件夹下创建一个 first.vue并仿照 App.vue 的格式和前面学到的知识写一个组件。
<template>
<div class="first">
<h1>{{ msg }}</h1>
<p>
<h1>姓名 : {{your_name}}</h1>
<!-- 方法 -->
<h1>{{details()}}</h1>
</p>
</div>
</template>
<script>
export default {
name: 'first',
data() {
return {
msg: "这是我的第一个vue页面!",
your_name: "wilieer"
}
},
methods: {
details: function() {
return this.msg + " - VUE学习"
}
}
}
</script>
<style>
</style>
然后在App.vue使用组件 ( 因为在 index.html 里面定义了 id="app"所以就以这个组件作为主入口,方便 )
第一步,引入。
在script标签内的第一行写
import first from './components/first.vue'
第二步,注册。
在script标签内的 data 代码块后面加上 components: { first }。记得中间加英文逗号!!!
export default {
data () {
return {
msg: 'Hello Vue!'
}
},
components: { first }
}
第三步,使用。
在<template></template>内加上<first></first>
<template>
<div id="app">
<h1>{{ msg }}</h1>
<first></first>
</div>
</template>
完成后的代码:
<!-- 展示模板 -->
<template>
<div id="app">
<h1>{{ msg }}</h1>
<first></first>
</div>
</template>
<script>
// 导入组件
import first from './components/first.vue'
export default {
data () {
return {
msg: 'Hello Vue!'
}
},
components: { first }
}
</script>
<!-- 样式代码 -->
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
text-align: center;
}
</style>
这时候看看浏览器上的 http://localhost:8080/ 页面(之前打开过就会自动刷新),如果你没看到效果是因为你没有对 App.vue 和 firstcomponent.vue 进行保存操作,保存后页面会自动刷新。
大致效果如下:

本文详细介绍了如何在Vue项目中创建和使用自定义组件,包括组件的创建步骤、数据绑定、方法调用及在主组件中的引入、注册和使用过程。
1295

被折叠的 条评论
为什么被折叠?



