Vue组件通信实例分析

发布时间:2022-08-05 14:01:26 作者:iii
来源:亿速云 阅读:133

本文小编为大家详细介绍“Vue组件通信实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“Vue组件通信实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

一、组件间的通信方式分类

Vue组件通信实例分析

二、props传递数据

适用场景:父组件传递数据给子组件;

Person.vue

<template>
  <div>
    Person
    <Student1 name="jack" age="18"></Student1>
    </div>
</template>
<script>
import Student1 from './Student1'
export default {
    name: 'Person',
    components: {
        Student1,
    },
</script>

Student1.vue

<template>
  <div>
    Student1
    {{name}},{{age}}
  </div>
</template>
<script>
export default {
    name: 'Student1',
    props: {
        name: String,
        age:Number,
    }
}
</script>

效果

Vue组件通信实例分析

三、$emit 触发自定义事件

Student1.vue

<template>
  <div>
    Student1
    <button @click="giveData()">点我传递数据</button>
  </div>
</template>
<script>
export default {
    name: 'Student1',
    methods: {
        giveData() { 
            this.$emit('add', '12345');
        }
    },
}
</script>

Person.vue

<template>
  <div>
    Person
    <Student1 @add="cartAdd($event)"></Student1>
    </div>
</template>
<script>
import Student1 from './Student1'
export default {
    name: 'Person',
    components: {
        Student1,
    },
    methods: {
        cartAdd(event) { 
            console.log(event);
        }
    },
}
</script>

四、ref标记

<template>
  <div>
    Person
    <Student2 ref="foo"></Student2>
    <button @click="getRef()">点击获取ref数据</button>
  </div>
</template>
<script>
import Student2 from "./Student2";
export default {
  name: "Person",
  components: {
    Student2,
  },
  methods: {
    getRef() {
      console.log(this.$refs.foo);
    },
  },
};
</script>

效果

Vue组件通信实例分析

五、EventBus事件总线

main.js

beforeCreate() {
  Vue.prototype.$bus = this
}

Student2.vue

<template>
  <div>
    Student2
    <button @click="getBus()">点我获取全局事件总线数据</button>
  </div>
</template>
<script>
export default {
  name: 'Student2',
  data() {
    return {
      name: 'fanafan',
      age:'17'
    }
  },
  methods:{
    getBus(){
      this.$bus.$emit('bus',this.name)
    }
  }
}
</script>

Student1.vue

mounted() {
    this.$bus.$on('bus', (data) => { 
        console.log(data)
    })
},

六、$parent 或 $root

使用方法类似全局事件总结

Vue.prototype.$parent = this
// 传数据
this.$parent.$emit('parent',this.age)
//接数据
this.$parent.$on('parent', (data) => {
    console.log(data);
})

七、vuex

读到这里,这篇“Vue组件通信实例分析”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Vue父子组件通信
  2. Vue兄弟组件通信

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:SpringBoot如何实现过滤敏感词

下一篇:JavaScript给数组添加元素的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》