vue-组件之间通信3种实例+“双向绑定”+v-model传值

vue的父组件与子组件实现数据通信的5种方式

一、父=>子

父:

<div>
  <child :child-str="data"></child>
</div>

import child from './school-child';
export default {
    name: "parent",
    components:{child},
    data(){
      return {
        data:'我要向子组件传递数据'
      }
    },
}

 

子:(子组件通过props来接受数据)

<div>我是子组件,接收父组件传递过来的值-{{childStr}}</div>
export default {
    name: "child",
    props:{
      childStr:{
        type:String,
        default:'我是空的'//如果不传值,显示的值
      }
    }
  }

二、子=>父(通过触发事件来改变组件的数据)

子:

<el-button @click="clickMe" type="primary">点击我传值</el-button>

methods:{
  clickMe(){
    this.$emit('clickStr','传递的值')
  }
}

<child @clickStr="showChild"></child>
methods:{
  showChild(msg){
    console.log(msg);
  }
}

三、兄弟之间通信(二者无关系)

兄弟1 => 兄弟2 通信,需要公共实例来做为桥梁

bus.js
import Vue from 'vue'
export default new Vue();

兄弟一

import Bus from '../../config/bus'
Bus.$emit('xiongdi','兄弟')

兄弟二

import Bus from '../../config/bus'
Bus.$on('xiongdi',(arg) => {
        console.log(arg);
      })

其他:VueX , provide / inject API, dispatch / broadcast 和 findComponents等。。。。

四、父子组件之间-可能需要对一个 prop 进行“双向绑定”,见官网

子组件传递

this.$emit('update:value',location);

父组件接收

 {{doc}}
<child  v-bind:value.sync="doc"/>

五、利用v-model实现通信:官网链接

目标:父组件、子组件按钮改变同一个内容showFlag,实现效果

父组件code

<template>
  <div>
    <h1>这是组件外面的内容:{{showFlag}}</h1>
    <button @click="showClick">父组件按钮</button>
    <test-child v-model="showFlag" ></test-child>
  </div>
</template>
<script>
  import testChild from './test-child'
  export default {
    name:'parent',
    components:{
      testChild
    },
    data(){
      return{
        showFlag:true
      }
    },
    methods:{
      showClick(){
        this.showFlag = !this.showFlag;
      }
    }
  }
</script>
<style lang="scss" scoped></style>

子组件 code

<template>
  <div>
    <div class="hello">
      <h1>这是子组件里面的内容 {{checked}}</h1>
      <button @click="close">子组件按钮</button>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'test-child',
    model: {
      prop: 'checked',
      event: 'change'
    },
    props: {
      checked: {
        type: Boolean
      }
    },
    methods: {
      close() {
        this.$emit('change', !this.checked);
      }
    }
  };
</script>

<style scoped>

</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值