Vue实现TodoList的方式:第二版——父子组件传参,组件化watch实现

在这里插入图片描述
父组件

<template>
  <div id="app">
    <div
      id="nav"
      style="border:solid 2px black"
    >
      <router-link to="/home">进入主页</router-link>
      <!-- <h1>parent父组件</h1>
      在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法
      <child v-on:listenToChildEvent="showMsgFromChild"></child> -->
      <div>
        <h1>我是TodoList2的父组件</h1>
        <input
          v-model="inputValue"
          type="text"
        />
        <button @click="addDataToList">添加</button>
        <!-- 显示子组件的结果 -->
        <list-item :list="list"></list-item>
      </div>
    </div>
    <router-view />
  </div>
</template>

<script>
// import child from './Card'
import ListItem from './TodoList2'
/**
 *1. 父组件引入子组件,父组件修改变量值
 */
export default {
  name: 'Welcome',
  data() {
    return {
      list: [],
      inputValue: ''
    }
  },
  components: {
    // child
    //显示子组件
    ListItem
  },
  created() {},
  mounted() {},
  methods: {
    // showMsgFromChild(msg) {
    //   console.log(msg)
    //   alert(msg)
    // }
    addDataToList() {
      if (this.inputValue.length === 0) {
        return '长度为0不添加'
      }
      this.list.push(this.inputValue)
      this.inputValue
    }
  },
  computed: {}
}
</script>

<style scoped lang="scss"></style>

子组件

<template>
  <div style="border:solid 2px blue">
    <h1>我是组件TodoList2</h1>
    <div
      v-for="(item, index) in list"
      :key="index"
      @click="delDataFromList(index)"
      style="cursor:pointer"
    >{{ item }}</div>
  </div>
</template>

<script>
export default {
  name: 'List',
  /**
   *
   * 本页面为子组件
   *
   *
   * 父子组件之间的通信就是 props down,events up,
   * 父组件通过 属性props向下传递数据给子组件,
   * 子组件通过 事件events 给父组件发送消息。
   */

  /**
   * 2.子组件通过props,引用指定的父组件的变量
   */
  props: {
    list: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      innerList: []
    }
  },
  watch: {
    /**
     *3. watch 是 Vue 侦听器,可以实时监控数据变化,进而响应数据变化。
       子组件通过 watch 监听父组件 props 的 list,将其变化后值赋给子组件数据。
        封装子组件 ListItem
     */
    list(val) {
      this.innerList = val
    }
  },
  components: {},
  created() {},
  mounted() {},
  methods: {
    delDataFromList(index) {
      this.innerList.splice(index, 1)
    }
  },
  computed: {}
}
</script>

<style scoped lang="scss"></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值