vue

您所在的位置:网站首页 前端emit vue

vue

#vue| 来源: 网络整理| 查看: 265

@Emit和@Prop属于vue-property-decorator库,使用时需要先导入

import { Component, Vue, Prop, Emit } from "vue-property-decorator";

1.父组件向子组件传值:

父组件代码:

import { Component, Vue } from "vue-property-decorator"; import childCom from "路径"; @Component({ components: { childCom // 声明子组件 } }) export default class Parent extends Vue { private msg: string = "要传给子组件的值"; }

子组件代码:

{{parentValue}} // 引入Prop import { Component, Vue, Prop } from "vue-property-decorator"; @Component export default class Child extends Vue { @Prop(String) // 括号里为父组件传来的值的类型 private parentValue: string; // 父组件传来的值用parentValue接收 prvate crated() { // 输出 console.log(this.parentValue); } }

注意:::如果是父组件向子组件动态传值(即变量)需要做以下更改:

子组件中接收变量的值需要有一个默认值,比如上面子组件中的代码:

@Prop(String) private parentValue: string = ""; // 这里默认给了一个空值

同时需要对这个变量进行监听,监听其变化:

@Watch("parentValue") private onParentValue(newValue: any) { // 输出变化后的值 console.log(newValue); }

2.子组件向父组件传值

子组件代码:

向父组件传值 向父组件传值 向父组件传值 // 引入Emit import { Component, Vue, Emit } from "vue-property-decorator"; @Component export default class Child extends Vue { // 子组件向父组件传的值 private msg: string = "要传递给父组件的值"; // 方法一 @Emit() private handleToParent1() { return this.msg; // return将要传递的值 } // 方法二: 注意,这时父组件接收值时是用@Emit("test")括号中的test接收的,test会把正面的方法名字覆盖。(test)是自定义的 @Emit("test") private handleToParent2() { return this.msg; // return将要传递的值 } // 方法三 // 先定义父组件接收的方法(同方法一、二) @Emit() private handleToParent3() { return this.msg; // return将要传递的值 } private handleClickEvent() { // ... 一些其它的操作 // 然后手动调用传值 this.handleToParent3(); } }

父组件代码:

import { Component, Vue } from "vue-property-decorator"; import childCom from "路径"; @Component({ components: { childCom // 声明子组件 } }) export default class Parent extends Vue { private msg: string = "要传给子组件的值"; private childValue: string = ""; // 处理子组件传过来的值 val:是自定义的 private handleChildValue(val: string) { // val: 子组件传过来的值 this.childValue = val; } }

如果要传递多个值,建议把这多个值封装成一个对象,然后一块传递。如:

// 子组件 @Emit() private test() { // 要传给父组件的多个值 const params = { param1: value1, param2: value2, // ...... }; return params; }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3