vue 框架的组件与组件通信方法
作者:Changing Lin
- 2021 年 12 月 02 日
本文字数:1653 字
阅读完需:约 5 分钟
1.常见的通信场景
一套用于构建用户界面的渐进式框架
同层级的组件
父组件与子组件
子组件与父组件
2.常见的通信方法
props:可以给当前组件定义属性,并且允许父组件在调用的时候,调用对应的属性传值给子组件
// myinput.vue 子组件的声明props属性字段<template> <view class='parent'> <text class='tip-text'>{{tip}}</text> <view class="picker-parent"> <input :id='tip' class='tip-input' style="border: 0px; height:78rpx;line-height:78rpx;margin-left:1rpx;" :maxlength="maxlength" name="name" v-model="value" @input="inputFunc" :type="type" :placeholder='placeholder' :disabled="disabled"/> </view> </view></template>
<script> export default { name: 'myinput', data() { return { value: '', disabled: false, type: 'text' }; }, computed:{ isShowImage: function() { return false }, }, props: { tip: { type: String, required: true }, maxlength: { type: Number, required: true }, placeholder: { type: String, required: true }, inputCallback: { type: Function, required: true }, initValue:{ type: String, required: false }, initType:{ type: String, required: false } }, mounted() { let initValue = this.initValue let initType = this.initType if(!isNil(initValue)){ this.value = initValue this.disabled = true } if(!isNil(initType)){ this.type = initType } }, methods:{ inputFunc(e){ this.$props.inputCallback(e.target.id, e.detail.value) }, resetDisabled(){ // 表示 复位 disabled禁用属性 // console.log("父组件调用了我", this.disabled) this.disabled = false } } }</script>
// page.vue 父组件调用myinput组件,并且传递参数给子组件<template> <view class="container"> <myinput class="tip_input-parent" style="margin-top: 40rpx;" :tip="name.key" :initValue="name.value" maxlength="8" placeholder="请输入最多8个字符" :inputCallback="inputCallback" ref="name" ></myinput> </view></template>复制代码
自定义事件:
// 发送事件uni.$emit("event", this.device, this.isChecked)
// 监听事件,一般在启动的时候调用uni.$on("event", (isChecked) => { console.warn("收到事件", isChecked)})
// 取消监听,一般在结束的时候调用uni.$off("event")复制代码
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
new Vue({ // state data () { return { count: 0 } }, // view template: ` <div>{{ count }}</div> `, // actions methods: { increment () { this.count++ } }})复制代码
这个状态自管理应用包含以下几个部分:
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
3.父组件调用子组件方法
parent.vue
<template> <div> <h1>我是父组件</h1> <child ref="child"></child> </div></template><script> import child from './child' export default{ components:{ child }, methods:{ parent(){ this.$refs.child.childFn() this.$.refs.child.childFn() } } }</script>复制代码
child.vue
<template> <div> <h2>我是子组件</h2> </div></template><script> import child from './child' export default{ components:{ child }, methods:{ childFn(){ alert('父组件调用了我') } } }</script>复制代码
划线
评论
复制
发布于: 7 小时前阅读数: 4
版权声明: 本文为 InfoQ 作者【Changing Lin】的原创文章。
原文链接:【http://xie.infoq.cn/article/5b226ccc036e2dd2c30ea3c80】。文章转载请联系作者。
Changing Lin
关注
获得机遇的手段远超于固有常规之上~ 2020.04.29 加入
我能做的,就是调整好自己的精神状态,以最佳的面貌去面对那些未曾经历过得事情,对生活充满热情和希望。











评论