目录结构
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vue-demo</title> </head> <body> <div class="app"></div> <!-- built files will be auto injected --> </body> </html>main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import TodoList from './TodoList' import router from './router' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '.app', router, components: { TodoList }, template: '<TodoList/>' })TodoList.vue文件
<template> <div> <input type="text" v-model="inputValue"> <button v-on:click="handleSubmit">提交</button> <ul> <todo-item v-for="(item,index) of list" :key="index" :content="item" :index="index" @delete="handleDelete"> </todo-item> </ul> </div></template><script> //导入componets下的组件todoItem.vue import todoItem from './components/todoItem' //局部组件的注册和声明,之后在本页面使用局部组件todo-item export default { components:{ 'todo-item':todoItem, }, data(){ return { inputValue:'', list:[] } }, methods:{ handleSubmit(){ this.list.push(this.inputValue) this.inputValue='' }, //点击ul下的li,删除对应的项,通过index标识 handleDelete(index){ this.list.splice(index,1) } }}</script><style></style>todoItem.vue文件 <template> <li v-on:click="handleDelte">{{content}}</li></template><script>export default {// 父子组件传值如此通信// 子组件通过props接收父组件传来的值 props:['content','index'], methods:{ handleDelte(){ console.log(this.index) // 子组件触发了事件出去,父组件那边需要监听并处理 this.$emit('delete',this.index) } }}</script><!-- Add "scoped" attribute to limit CSS to this component only --><style scoped></style>转载于:https://www.cnblogs.com/malong1992/p/11535081.html