Blogger Information
Blog 250
fans 3
comment 0
visits 323089
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Vue自学:组件子传父操作
梁凯达的博客
Original
1315 people have browsed it
  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  8. <title>Vue自学:组件子传父操作</title>
  9. </head>
  10. <body>
  11. <!-- 这里是个父组件 -->
  12. <div id="app">
  13. <!-- 使用v-on,但是绑定的属性是this.$emit所发送过去的监听事件,并非普通的click事件 -->
  14. <cpn v-on:item-click="cpnclick"></cpn>
  15. </div>
  16. </body>
  17. <!-- 这里是子组件模板 -->
  18. <template id="cpn">
  19. <div>
  20. <!-- 这里所使用的categories,是data这个函数内的遍历对象 -->
  21. <!-- v-on:click事件,用于绑定一个item,发送给父组件 -->
  22. <button v-for="item in categories" v-on:click="selfbtn(item)">{{item.name}}</button>
  23. </div>
  24. </template>
  25. <script type="text/javascript">
  26. //子组件
  27. const cpn = {
  28. // 绑定模板
  29. template:'#cpn',
  30. // 设置数据:必须为函数格式
  31. data(){
  32. // 返回的是一个数组对象类型的数据
  33. return {
  34. categories:[
  35. {id:'aaa',name:'kai'},
  36. {id:'bbb',name:'da'},
  37. {id:'ccc',name:'liang'},
  38. {id:'ddd',name:'bian'}
  39. ]
  40. }
  41. },
  42. methods:{
  43. //绑定了点击时间,形参为item
  44. selfbtn(item){
  45. //this.$emit('绑定新的事件','传递过去的值')
  46. this.$emit('item-click',item)
  47. }
  48. }
  49. }
  50. //父组件
  51. const app = new Vue({
  52. el:'#app',
  53. data:{
  54. },
  55. components:{
  56. //绑定的对象增强写法
  57. cpn
  58. },
  59. methods:{
  60. //将item传递过来
  61. cpnclick(item){
  62. console.log('cpnclick',item)
  63. }
  64. }
  65. })
  66. </script>
  67. </html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post