Vue 2.0 typescript 写法传值方式:
随着 typescript 越来越受到前端框架的关注,最近使用 vue + typescript 做了一个项目。发现写法与 vue + js 完全不一样。但是原理相同。接下来给大家介绍 Vue 开发中常用的传值方式。
Vue 常用的三种传值方式有:
父传子
子传父
非父子传值
引用官网的一句话:父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息,如下图所示:
接下来,我们通过实例来看可能会更明白一些:
1. 父组件向子组件进行传值
父组件
// 父组件
import {Component, Prop, Vue} from "vue-property-decorator";
import About from "@/views/About.vue";
@Component({ // 引入子组件
components: {
About
}
})
export default class HelloWorld extends Vue {
value: string = "我是父组件哦";
created() {
}
}
子组件
// 子组件
子组件:{{value}}
import {Component, Prop, Vue} from "vue-property-decorator";
@Component
export default class About extends Vue {
// 接受父组件的值
@Prop({
type: String, // 父组件传递给子组件的数据类型
required: false, // 是否必填
default: ' ' // 默认值, 如果传入的是 Object,则要 default: ()=>({}) 参数为函数
}) value !: string;
created() {}
}
2. 子组件向父组件传值
父组件
.// 父组件
import {Component, Vue} from "vue-property-decorator";
import About from "@/views/About.vue";
@Component({
components: {
About
}
})
export default class HelloWorld extends Vue {
msg: string = '';
created() {};
// 接收子组件发送数据是 触发的事件
propMsg(msg: string){
this.msg = msg;
}
}
子组件
// 子组件
子组件:我的子组件的数据 点击给父组件发送数据
import {Component, Emit, Vue} from "vue-property-decorator";
@Component
export default class About extends Vue {
msg: string = '子组件的msg数据';
// bindSend 为父组件引用子组件上 绑定的事件名称
@Emit('bindSend') send(msg: string){}; // send 处理给父组件传值的逻辑
created() {}
// 通过触发这个事件来处理发送的内容数据的逻辑,然后执行 @Emit() 定义的 sen(msg: string){} 事件
propMsg(){
this.msg = '子组件的msg数据,被传给了父组件';
this.send(this.msg)
}
}
@Emit('bindSend') send(msg: string){}; // send 处理给父组件传值的逻辑 和 $emit一样的效果this.$emit('childFn', this.message);
3. 兄弟组件向传值
这里我们实现的思路是: (1)其中一个兄弟组件向父组件发送数据; (2)然后父组件再向另一个兄弟组件传值;