博客列表 >组件注册与组件之间的通信

组件注册与组件之间的通信

风车
风车原创
2022年08月13日 18:20:38565浏览

组件

组件允许我们将 UI 划分为独立的、可重用的部分,并且可以对每个部分进行单独的再次重新编辑,就如同一个树状解构,一层一层的组合

组件的注册

vue指令的本质是自定义标签属性
vue组件的本质就是自定义标签

组件的注册有两种方式

1.全局组件
大量复用的组件建议注册成全局组件
全局组件注册在vue实例上
使用 .component(第一个参数是组建名称,第二个参数是组建定义(第二个是一个函数))

  1. <template id="counter">
  2. <button @click="count++">点赞: {{count}}</button>
  3. </template>
  4. <script>
  5. app.component('button-counter', {
  6. //将上方的coubter与template绑定
  7. template: '#counter',
  8. data() {
  9. return {
  10. count: 0,
  11. };
  12. },
  13. });
  14. </script>

2.局部组件
不常用的组件建议注册成局部组件
局部组件注册在vue实例的参数中

  1. const app = Vue.createApp({
  2. components: {
  3. // 这里使用规范的驼峰命名法, 但是在html中要转为蛇形
  4. buttonCounter: {
  5. template: '#counter',
  6. data() {
  7. return {
  8. count: 0,
  9. };
  10. },
  11. },
  12. },
  13. });
  14. app.mount('#app');

组件的传参(通信)

父组件向子组件传参

  1. <body>
  2. <div id="app">
  3. <!-- 使用自定义属性将父组件参数传入子组件中 -->
  4. <button-counter username="admin" email="498446472@qq.com"></button-counter>
  5. </div>
  6. <template id="counter">
  7. <p>用户名: {{username}}</p>
  8. <p>邮箱: {{email}}</p>
  9. </template>
  10. <script>
  11. const app = Vue.createApp();
  12. app.component('button-counter', {
  13. // props: 用数组接收父组件传入的自定义属性做为载体的参数
  14. props: ['username', 'email'],
  15. template: '#counter',
  16. });
  17. app.mount('#app');
  18. </script>

子组件像父组件传参(监听子组件事件)

  1. <div id="app">
  2. <button-counter @review-count="review"></button-counter>
  3. </div>
  4. <template id="counter">
  5. <button @click="count++">点赞: {{count}}</button>
  6. <!-- 发布订阅 -->
  7. <!-- $emit(自定义事件名称, 向父组件传递的参数(可选)) -->
  8. <!-- $emit('reviewCount', this.count) -->
  9. <button @click="$emit('reviewCount', this.count)">评价</button>
  10. </template>
  11. <script>
  12. const app = Vue.createApp({
  13. methods: {
  14. review(count) {
  15. console.log(count);
  16. if (count >= 10) alert('大家吃了吗?');
  17. },
  18. },
  19. });
  20. app.component('button-counter', {
  21. template: '#counter',
  22. data() {
  23. return {
  24. count: 0,
  25. };
  26. },
  27. });
  28. app.mount('#app');

父->子: props: [….]
子->父:
1 子发布事件: $emit(自定义事件,参数(参数可选))
2 父订阅事件: @自定义事件(…args)

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议