博客列表 >vue组件注册/组件之间的传值

vue组件注册/组件之间的传值

汇享科技
汇享科技原创
2022年08月06日 10:33:55393浏览

vue组件注册

  • 全局组件:注册在vue实例上的 使用实例名.component('模板名称',{template:'模板内容'...})

l6h8nnk7.png

  • 局部组件:注册在vue实例选项上的 在内部使用components定义

l6h8q3sh.png

  1. <div id="app">
  2. <blog-text></blog-text>
  3. </div>
  4. <template id="box">
  5. <table>
  6. <thead>
  7. <tr>
  8. <th>姓名</th>
  9. <th>年龄</th>
  10. <th>婚否</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. <tr v-for="(v,k) of shuju">
  15. <td>{{v.name}}</td>
  16. <td>{{v.age}}</td>
  17. <td v-if="v.hun===true">已婚</td>
  18. <td v-if="v.hun===false">未婚</td>
  19. </tr>
  20. </tbody>
  21. </table>
  22. </template>
  1. //全局组件:注册在VUE实例上的
  2. const app = Vue.createApp();
  3. app.component("blog-text", {
  4. template: "#box",
  5. data() {
  6. return {
  7. shuju: [
  8. {
  9. name: "小王",
  10. age: 18,
  11. hun: false,
  12. },
  13. {
  14. name: "小刘",
  15. age: 20,
  16. hun: false,
  17. },
  18. {
  19. name: "小张",
  20. age: 25,
  21. hun: true,
  22. },
  23. ],
  24. };
  25. },
  26. });
  27. //局部组件:注册在VUE实例内部选项内的
  28. const app = Vue.createApp({
  29. components: {
  30. blogText: {
  31. template: "#box",
  32. data() {
  33. return {
  34. shuju: [
  35. {
  36. name: "小王",
  37. age: 18,
  38. hun: false,
  39. },
  40. {
  41. name: "小刘",
  42. age: 20,
  43. hun: false,
  44. },
  45. {
  46. name: "小张",
  47. age: 25,
  48. hun: true,
  49. },
  50. ],
  51. };
  52. },
  53. },
  54. },
  55. });
  56. app.mount("#app");

组件传值

  • 父组件->子组件传值

l6h91gk3.png

  1. <div class="app">
  2. <blog-text username="admin" email="admin@qq.com"></blog-text>
  3. </div>
  4. <template id="box">用户名:{{username}}:邮箱:{{email}}</template>
  1. const app = Vue.createApp();
  2. app.component("blog-text", {
  3. //通过props接收组件传过来的值
  4. props: ["username", "email"],
  5. template: "#box",
  6. });
  7. app.mount(".app");
  • 子组件->父组件传值/监听子组件事件

l6ha3phh.png

  1. <div class="app">
  2. <blog-text @panduan="review"></blog-text>
  3. </div>
  4. <template id="box">
  5. <button @click="cont++">点赞:{{cont}}</button>
  6. <button @click="$emit('panduan',this.cont)">评价</button>
  7. </template>
  1. const app = Vue.createApp({
  2. methods: {
  3. review(e) {
  4. // console.log(e);
  5. if (e >= 10) {
  6. // console.log(111);
  7. alert("谢谢您的评价");
  8. }
  9. },
  10. },
  11. });
  12. app.component("blog-text", {
  13. template: "#box",
  14. data() {
  15. return {
  16. cont: 0,
  17. };
  18. },
  19. });
  20. app.mount(".app");
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议