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

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

吴长清
吴长清原创
2022年08月08日 18:08:19303浏览

1.组件注册

组件注册可以在vue的实例上进行全局注册,也可以在vue的选项中进行局部注册
组件注册方法如下:声明-注册-使用

  1. <div class="app">
  2. <!-- 使用组件 -->
  3. <button-counter></button-counter>
  4. <title-components></title-components>
  5. <user-info-components></user-info-components>
  6. </div>
  7. <!-- 组件声明 -->
  8. <template id="counter">
  9. <button @click="count++">点赞:{{count}}</button>
  10. </template>
  11. <template id="userInfo">
  12. <p>用户名: {{username}}</p>
  13. <p>邮箱: {{email}}</p>
  14. </template>
  15. <script>
  16. const app = Vue.createApp({
  17. //局部注册
  18. components: {
  19. userInfoComponents: {
  20. // 声明组件的id
  21. template: "#userInfo",
  22. data() {
  23. return {
  24. username: "张三",
  25. email: "zhangsan@qq.com",
  26. };
  27. },
  28. },
  29. titleComponents: {
  30. // 可以直接使用html标签声明
  31. template: `<h3>{{title}}</h3>`,
  32. data() {
  33. return {
  34. title: "用户信息",
  35. };
  36. },
  37. },
  38. },
  39. });
  40. //全局注册
  41. app.component("buttonCounter", {
  42. // 声明组件的id
  43. template: "#counter",
  44. data() {
  45. return {
  46. count: 0,
  47. };
  48. },
  49. });
  50. app.mount(".app");
  51. </script>

2.组件之间的通讯

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

  1. <div id="app" class="demo">
  2. <p>姓名: {{ name }}</p>
  3. <p>邮箱: {{ email }}</p>
  4. <!-- v-model 数据双向绑定 接收子组件传的参数 -->
  5. <!-- 同时将name 和 email 的值传给子组件 -->
  6. <!-- @alter-msg 自定义事件 alterMsg 定义函数来接收子组件传来参数 -->
  7. <user-data v-model:name="name" v-model:email="email" @alter-msg="alterMsg"></user-data>
  8. </div>
  9. <!-- 组件声明 -->
  10. <template id="userInfo">
  11. <!--$emit('update:name', $event.target.value) 当input的值发生改变时向父组件传参 -->
  12. <input type="text" :value="name" @input="$emit('update:name', $event.target.value)" />
  13. <br />
  14. <input type="text" :value="email" @input="$emit('update:email', $event.target.value)" />
  15. <br />
  16. <!-- 传参 -->
  17. <!-- $emit('alterMsg',[this.name,this.email]) -->
  18. <!-- alterMsg 自定义事件 -->
  19. <!-- [this.name,this.email] 数组参数 -->
  20. <button @click="$emit('alterMsg',[this.name,this.email])">查看用户信息</button>
  21. </template>
  22. <script>
  23. const HelloVueApp = {
  24. data() {
  25. return {
  26. name: "张三",
  27. email: "zhangsan@qq.com",
  28. };
  29. },
  30. components: {
  31. userData: {
  32. // 接收父组件userData传来的数据
  33. props: ["name", "email"],
  34. template: "#userInfo",
  35. },
  36. },
  37. methods: {
  38. //函数方法,接收父组件传的参数
  39. alterMsg(arr) {
  40. alert("姓名:" + arr[0] + " ,邮箱:" + arr[1]);
  41. },
  42. },
  43. };
  44. Vue.createApp(HelloVueApp).mount("#app");
  45. </script>

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