定义组件
1.
在程序的
components
目录下新建一个名为
Child.vue
的文件
2.
在文件内键入如下代码
<template>
<div>
Child
</div>
</template>
<script>
export default {
name: 'Child'
}
</script>
新建的 Child .vue 文件即为我们定义的组件, 文件的位置一般放在 src 目录下的 components 目录下
在App.vue文件内注册Child.vue组件
1.
首先将组件引入到
App.vue
文件内
import Child from './components/Child'
注意:组件引入时不需要使用后缀名.vue
2.
在
App.vue
模块内添加一个名为
components
的属性
3.
将组件注册到
App.vue
文件内
components: {Child}
4.
在
template
标签内使用
Child
组件
< Child />
Vue组件之间的传值
父子组件通信
如何定义父子组件?
将其他组件以import引入用自定义标签接收,在当前组件中component里注册该标签,页面上可以直接用<自定义标签></自定义标签>样子使用。当前组件为父组件,被引入的组件为子组件。
父组件向子组件传值
一般在子组件内定义props来做接收
即:
props: ['msg']
Child
.vue
文件代码变更如下:
定义好
props
之后我们可以在父组件传递
props
参数
<template>
<div>
<h2>子组件,嵌套到一个页面的内部使用</h2>
接收到父组件传递的参数值:<b>{{msg}}</b><br>
您的姓名是:{{name}},年龄:{{age}}<br>
</div>
</template>
<script>
export default({
name: 'Child',
//定义属性,其他页面调用该组件时,可以通过属性名称返回值
props:[
"msg",
"name",
"age"
]
})
</script>
父组件代码如下
<template>
<div>
<h2>父组件加载子组件</h2>
<hr>
<!--3.调用子组件,并且向子组件传递参数-->
<Child msg="父组件传递给子组件的参数" name="张三" age="20"/>
</div>
</template>
<script>
/*
1.导入子组件
*/
import Child from '../../components/Child'
export default ({
name: 'Parent',
//2.注册子组件
components:{
Child
}
})
</script>
子组件向父组件传值
子组件通过调用 this.$emit() 方法向父组件传值基本语法:this.$emit('func', param)func: 为父组件中绑定的函数名,可自定义param: 为要传递的参数<Child @func=”funcHandle”>其中 funcHandle 需在父组件中定义好相应的方法,该方法接收一个或多个参数funcHandle(val) {this.msg = val}
子组件修改代码如下:
this.$emit('parentFunc',this.title);
父组件修改代码如下:
<Child msg="父组件传递给子组件的参数" name="张三" age="20" @parentFunc="receFunc"/>
methods:{
receFunc(val){
this.title = val
}
}
Child.vue完整代码
<template>
<div>
<h2>子组件,嵌套到一个页面的内部使用</h2>
接收到父组件传递的参数值:<b>{{msg}}</b><br>
您的姓名是:{{name}},年龄:{{age}}<br>
标题:<input type="text" v-model="title">
<input type="button" @click="test()" value="返回值给父组件">
</div>
</template>
<script>
export default({
name: 'Child',
//定义属性,其他页面调用该组件时,可以通过属性名称返回值
props:[
"msg",
"name",
"age"
],
data(){
return {
title:''
}
},
methods:{
test(){
//调用父组件的函数,同时传回参数
//parentFunc父组件的函数
// alert(this.title)
this.$emit('parentFunc',this.title);
}
}
})
</script>
parent.vue完整代码
<template>
<div>
<h2>父组件加载子组件</h2>
<hr>
<!--3.调用子组件,并且向子组件传递参数-->
<Child msg="父组件传递给子组件的参数" name="张三" age="20" @parentFunc="receFunc"/>
子组件返回的值是:{{title}}
<h3 align="left">子组件传参给父组件的实现步骤</h3>
<hr>
<p align="left">
1.在parent.vue文件定义接受函数:receFunc<br>
2.定义调用组件时的事件的名称@parentFunc,该名称自定义<br>
3.在parent.vue文件调用子组件:<Child msg="父组件传递给子组件的参数" name="张三" age="20" @parentFunc="receFunc"/><br>
4.在child.vue文件定义test函数,利用$emit方法调用函数:this.$emit('parentFunc',this.title);返回子组件的值<br>
5.parentFun名称为自定义,主要parent.vue,child.vue两边使用的名称一致即可
</p>
</div>
</template>
<script>
/*
1.导入子组件
*/
import Child from '../../components/Child'
export default ({
name: 'Parent',
//2.注册子组件
components:{
Child
},
data(){
return{
title:''
}
},
methods:{
receFunc(val){
this.title = val
}
}
})
</script>