Vue学习日记02

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

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 进行保存操作,保存后页面会自动刷新。

大致效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值