• Vue中组件间的传值(子传父,父传子)


    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>TodoListtitle>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js">script>
    head>
    <body>
       
       <div id="app">
           <input type="text" v-model="inputValue">
           <button v-on:click="handleBtnClick">提交button>
           <ul>
               
               
               <todo-item v-bind:content="item" 
                          v-bind:index="index"
                          v-for="(item,index) in list" @delete="handleItemDelete">
                todo-item>
           ul>
       div>
        
       <script>
           // 父传子-在父组件使用子组件的地方通过v-bind进行传值,在子组件中通过props进行接受传过来的值。
           // 子传父-在子组件中通过$emit向外抛出一个事件,通过在父组件使用子组件的地方监听该事件,就要拿到子组件传过来的值。
           // 在写Vue代码的时候不要直接操作DOM,而是要通过数据的改变,让页面去自动更正变化。
    
           // 创建全局组件的一个方法Vue.component
           Vue.component('TodoItem',{
               props: ['content','index'],                    // 接收外部传入的v-bind:content的值,父组件todo-item向子组件TodoItem传值
               template:"
  • {{content}}
  • "
    , // 1创建一个模板。v-on:click简写@click,v-bind:可以简写为: methods:{ handleItemClick:function(){ this.$emit('delete',this.index) // 2当点击子组件的时候,子组件会向外出发一个delete事件,在父组件中创建子组件的同时,可以去监听delete事件 } } }); var app = new Vue({ el:'#app', data:{ list:[], inputValue:'' }, methods:{ handleBtnClick:function(){ this.list.push(this.inputValue); this.inputValue = ''; }, handleItemDelete:function(index){ // 4定义删除方法,使用index作为参数 // this.list = [] // 清空所有数据 this.list.splice(index,1) // 传入的数据下标减一 } } })
    script> body> html>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
  • 相关阅读:
    基于STM32单片机电子相册设计全套资料
    oracle 与mysql兼容日期(格式:YYYY年MM月DD日)
    Neo4J超详细专题教程,快来收藏起来吧
    Java基础之SimpleDateFormat的多线程陷阱
    华为云云服务器云耀L实例评测 | 在华为云耀L实例上搭建电商店铺管理系统:一次场景体验
    Java基于SpringBoot 的汽车租赁系统
    uboot常见函数
    Python_数据容器_元组tuple
    2022Nginx进阶教程,由浅入深
    RK3588平台开发系列讲解(视频篇)ffmpeg 的移植
  • 原文地址:https://blog.csdn.net/blbyu/article/details/126416635