vue中组件间通信的6种方式

组件是 vue.js最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互进行直接的引用,所以组件间的相互通信是非常重要的。

1.props / $emit

父组件通过 props 向子组件传递数据,子组件通过 $emit 和父组件通信。

(1)父组件向子组件传值(props的用法)

props的特点:

1.props只能是父组件向子组件进行传值,props使得父子组件之间形成一个单向的下行绑定。子组件的数据会随着父组件的更新而响应式更新。
2.props可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以是传递一个函数。
3.props属性名规则:若在props中使用驼峰形式,模板中标签需要使用短横线的形式来书写。

父组件:

// 父组件
<template>
    <div id="father">
        <son :msg="msgData" :fn="myFunction"></son>
    </div>
</template>

<script>
import son from "./son.vue";
export default {
    name: father,
    data() {
        msgData: "父组件数据";
    },
    methods: {
        myFunction() {
            console.log("vue");
        }
    },
    components: {
        son
    }
};
</script>

子组件:

// 子组件
<template>
    <div id="son">
        <p>{{msg}}</p>
        <button @click="fn">按钮</button>
    </div>
</template>
<script>
export default {
    name: "son",
    props: ["msg", "fn"]
};
</script>

(2)子组件向父组件传递数据($emit的用法)

$emit的特点:

$emit 绑定一个自定义事件,当这个事件被执行的时候就会将参数传递给父组件,而父组件通过v-on监听并接收参数

父组件:

// 父组件
<template>
  <div class="section">
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
    <p>{{currentIndex}}</p>
  </div>
</template>

<script>
import comArticle from './test/article.vue'
export default {
  name: 'comArticle',
  components: { comArticle },
  data() {
    return {
      currentIndex: -1,
      articleList: ['红楼梦', '西游记', '三国演义']
    }
  },
  methods: {
    onEmitIndex(idx) {
      this.currentIndex = idx
    }
  }
}
</script>

子组件:

//子组件
<template>
  <div>
    <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
  </div>
</template>

<script>
export default {
  props: ['articles'],
  methods: {
    emitIndex(index) {
      this.$emit('onEmitIndex', index) // 触发父组件的方法,并传递参数index
    }
  }
}
</script>

2、ref / $refs

<template>
  <child ref="child"></component-a>
</template>
<script>
  import child from './child.vue'
  export default {
    components: { child },
    mounted () {
      console.log(this.$refs.child.name);  // JavaScript
      this.$refs.child.sayHello();  // hello
    }
  }
</script>

子组件:

export default {
  data () {
    return {
      name: 'JavaScript'
    }
  },
  methods: {
    sayHello () {
      console.log('hello')
    }
  }
}

3.$parent / $children

使用$parent可以让组件访问父组件的实例(访问的是上一级父组件的属性和方法)。
使用 $children 可以让组件访问子组件的实例,但是, $children 并不能保证顺序,并且访问的数据也不是响应式的。

父组件:

<template>
  <div class="hello_world">
    <div>{{msg}}</div>
    <child></child>
    <button @click="change">点击改变子组件值</button>
  </div>
</template>

<script>
import child from './child.vue'
export default {
  components: { child },
  data() {
    return {
      msg: 'Welcome'
    }
  },
  methods: {
    change() {
      // 获取到子组件
      this.$children[0].message = 'JavaScript'
    }
  }
}
</script>

子组件:

<template>
  <div>
    <span>{{message}}</span>
    <p>获取父组件的值为:  {{parentVal}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Vue'
    }
  },
  computed:{
    parentVal(){
      return this.$parent.msg;
    }
  }
}
</script>

在上面的代码中,子组件获取到了父组件的parentVal值,父组件改变了子组件中message的值。

注意:

通过 $parent 访问到的是上一级父组件的实例,可以使用 $root 来访问根组件的实例在组件中使用$children拿到的是所有的子组件的实例,它是一个数组,并且是无序的在根组件 #app 上拿 $parent 得到的是 new Vue()的实例,在这实例上再拿 $parent 得到的是undefined,而在最底层子组件拿 $children 是个空数组$children 的值是数组,而 $parent是个对象。

4.$attrs / $listeners

$attrs,包含了父组件作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外);当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件。
$listeners,包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器,它可以通过v-on="$listeners" 传入内部组件。

父组件:

<template>
  <div id="app">
    <CompA title="123"></CompA>
  </div>
</template>
<script>
 import CompA from "./components/CompA";
export default {
  name: 'App',
  components: {
    CompA,
  },
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

子组件一:

<template>
  <div>
    CompA
    <!-- 通过$attrs传给CompB,CompC -->
    <!-- $attrs收集属性 $listeners收集事件-->
    <CompB title="my name is CompA" v-bind="$attrs" v-on="$listeners"></CompB>
  </div>
</template>
<script>
import CompB from "./CompB";
export default {
  // 爷爷要给孙子CompA传话
  //和$attrs结合起来用
 inheritAttrs: false,  
  components: {
    CompB,
  },
  mounted () {
    //   attrs  如果没有在props里面定义的参数,都会到这里来
      console.log(this.$attrs);
      console.log(this);
  },
};
</script>
<style scoped>
</style>

子组件二:

<template>
    <div>
        CompB
        <CompC v-bind="$attrs"></CompC>
    </div>
</template>
<script>
import CompC from "./CompC";
    export default {
        components: {
            CompC,
        },
        mounted () {
            console.log(this.$attrs);
            console.log(this.$listener);
        },
    }
</script>
<style lang="scss" scoped>
</style>

inheritAttrs

默认值为true,继承所有的父组件属性除props之外的所有属性。
只继承class属性。

5.依赖注入(provide / inject)

这种方式就是vue中依赖注入,该方法用于 父子组件之间 的通信。当然这里所说的父子不一定是真正的父子,也可以是祖孙组件,在层数很深的情况下,可以使用这种方式来进行传值。就不用一层一层的传递数据了。

provide和inject是vue提供的两个钩子,和data、methods是同级的。并且provide的书写形式和data一样。

provide钩子用来发送数据或方法。
inject钩子用来接收数据或方法

父组件:

provide() { 
    return {     
        num: this.num  
    };
}

子组件:

inject: ['num']

依赖注入所提供的属性是非响应式的

6.vuex

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值