22_components_组件向外部穿参.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="./js/vue.js"></script>
  8. <style>
  9. .box {
  10. width: 100px;
  11. height: 100px;
  12. background-color: red;
  13. margin: 10px;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div id="app">
  19. <box v-on:comhandle="parentHandle" val="helloworld"></box>
  20. <!-- <box v-bind:val="str"></box> -->
  21. <h1>文本框里面的值:{{childVal}}</h1>
  22. </div>
  23. <template id="box-temp">
  24. <div class="container">
  25. <div class="box">
  26. <span>{{val}}</span>
  27. <input type="text" v-model="num">
  28. <button @click="emitVal">传参</button>
  29. </div>
  30. </div>
  31. </template>
  32. <script>
  33. let app = new Vue({
  34. el: '#app',
  35. data: {
  36. str:"lovecoding",
  37. childVal:""
  38. },
  39. methods: {
  40. parentHandle(i) {
  41. this.childVal = i;
  42. console.log("父组件接收到了子组件的参数",i);
  43. }
  44. },
  45. components: {
  46. box: {
  47. template: "#box-temp",
  48. // 组件内部的data是个函数 内部返回一个对象
  49. data() {
  50. return{
  51. num:""
  52. }
  53. },
  54. // props用来接受传递进来的参数
  55. props:["val"],
  56. methods: {
  57. box1Handle() {
  58. console.log(this.val)
  59. },
  60. emitVal(){
  61. // 通过$emit触发父组件中的自定义事件
  62. this.$emit("comhandle",this.num);
  63. console.log(this.num)
  64. }
  65. }
  66. }
  67. }
  68. })
  69. </script>
  70. </body>
  71. </html>