vue+typescript实现todo list示例

  本例通过在页面中展示todo list列表,通过点击添加按钮,实现弹窗添加列表数据,实现父子组件之间的数据交换。

1、主页面代码如下:

<template>
  <div style="margin-top:20px;">
    <el-button @click="testFunc">添加</el-button>
    <p v-for="(item,index) in data" :key="item">{{item}} <span><i class="el-icon-delete-solid" style="color:#cccccc" @click="delData(index)"></i></span></p>
    <addContent :visible.sync="visible" @test="addData"></addContent>
  </div>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import addContent from '@components/addContent.vue';

@Component({  // 外部组件注册
  name: 'hello', // 本组件名称
  components: {
    addContent,
  },
})
export default class Hello extends Vue {
  private data: any [] = [1, 2 ];  // 本组件数据声明
  private visible: boolean = false;

  public testFunc(e: any): void {  //事件定义
    this.visible = true;
  }

  public addData(content: string): void { // 添加数据事件
    if (content) {
      this.data.push(content);
    }
  }

  private delData(index: any): void {
    this.data.splice(index, 1);
  }

}
</script>

  2、弹窗组件代码如下:

<template>
  <el-dialog :visible="view" width="400px" @close="visibleEmit">
    <template>
      <h3>{{testData}}</h3>
      <el-input v-model.trim="content"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visibleEmit">取 消</el-button>
        <el-button type="primary" @click="addData">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { Component, Vue, Prop, Emit } from 'vue-property-decorator';

@Component
export default class AddContent extends Vue {
  /**
   * 获取父组件传值
   */
  @Prop(Boolean)
  private visible: boolean = false;
  /**
   * 本组件数据变量定义
   */
  private content: string = '';

  /**
   * 计算属性定义
   */
  get view() {
    return this.visible;
  }

  get testData(): string {
    return '添加数据';
  }
  /**
   * 触发父组件事件,该处为父组件传递事件名称
   */
  @Emit('test')
  private addData(): string {
    const content = this.content;
    this.content = '';
    this.visibleEmit();
    return content;
  }
  /**
   * 触发父组件事件,更新.sync数据的值,适用于v-model绑定数据的组件间传值
   */
  @Emit('update:visible')
  private visibleEmit(): boolean {
    return false;
  }
}
</script>

  

猜你喜欢

转载自www.cnblogs.com/zhang134you/p/10951164.html