Vue学习笔记3.1 子-父组件传递数据 v-bind、v-on、$emit()

子向父传递组件:

示例:

在通过点击列表元素后自动删除所点击的列表。

先放完整的代码先:

<!DOCTYPE html>
<html>
<head>
  <title>TodoList</title>
  <script src="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" v-on:delete="handleItemDelete"></todo-item>
    </ul>
  </div>
</body>
<script>

var TodoItem = {
  props: ['content', 'index'],
  template: "<li v-on:click='handleDeleteClick'>{{content}}</li>",
  methods: {
    handleDeleteClick: function() {
      this.$emit('delete', this.index)
    }
  }
}

  var app = new Vue({
    el: "#app",
    data: {
      List: [],
      inputvalue: ''
    },
    methods: {
      handleBtnClick: function() {
        this.List.push(this.inputvalue)
        this.inputvalue = ''
      },
      handleItemDelete: function(index){
        this.List.splice(index, 1)
      }
    },
    components: {
      TodoItem: TodoItem
    }
  })
</script>
</html>

 

1.子组件建立点击事件发生数据变更函数触发:

    $emit()中的第一个参数是事件名(名字随便取),第二个是传出的参数

var TodoItem = {
  props: ['content', 'index'],
  template: "<li v-on:click='handleDeleteClick'>{{content}}</li>",
  methods: {
    handleDeleteClick: function() {
      this.$emit('delete', this.index)
    }
  }
}

2.父组件通过监听delete(根据$emit中的第一个参数名字来决定)

      <todo-item v-bind:content="item" v-bind:index="index" v-for="(item,index) in List" v-on:delete="handleItemDelete"></todo-item>

3.根据监听delete的函数进行数据处理完成子-父传递数据的过程:

      handleItemDelete: function(index){
        this.List.splice(index, 1)
      }

对了 v-bind==:

v-on==@ 也就是说

v-bind:content="item"   == :content="item"

v-on:click="handleBtnClick == @click="handleBtnClick

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@凌晨三点半

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值