- <template>
- <div>
- Child
- </div>
- </template>
- <script>
- export default {
- name: 'Child'
- }
- </script>
新建的 Child .vue 文件即为我们定义的组件, 文件的位置一般放在 src 目录下的 components 目录下
import Child from './components/Child'
components: {Child}
< Child />
props: ['msg']
- <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: 为要传递的参数 其中 funcHandle 需在父组件中定义好相应的方法,该方法接收一个或多个参数funcHandle(val) {this.msg = val}
子组件修改代码如下:
this.$emit('parentFunc',this.title);
父组件修改代码如下:
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>