初识Vue-cli
先说下下面代码中用到几个知识点
1.props
父组件通过props讲数据传递给子组件。
<!--父组件--> <template> <div> <ul> <todo-item v-for="(item,index) in list" :content="item" :index="index" ></todo-item> </ul> </div>
</template>
<!--子组件 通过props接受父组件传递的数据--> <script>
export default { props:['content','index'], methods:{ Delete(){ this.$emit('delete1',this.index) } } } </script>
2.$emit()
子组件通过$emit触发父组件自定义事件
<!--子组件 触发click事件后,会自动触发delete1--> <template> <li @click="Delete">{{content}}</li> </template> <script> export default methods:{ Delete(){ this.$emit('delete1',this.index) } } } </script> <!--父组件 当子组件 触发click事件后,会自动触发自定义delete1事件--> <template> <div> <ul> <todo-item @delete1="handledete"></todo-item> </ul> </div> </template>
All code:
<!--父组件--> <template> <div> <div> <input v-model="inputVuale"/> <button v-on:click="handleSubmit">提交</button> </div> <ul> <todo-item v-for="(item,index) in list" :content="item" :index="index" @delete1="handledete"></todo-item> </ul> </div> </template> <script> import TodoItem from './components/TodoItem' export default { components:{ 'todo-item':TodoItem }, data(){ return{ inputVuale:'', list:[] } }, methods:{ handleSubmit(){ this.list.push(this.inputVuale) this.inputVuale='' }, handledete(index){ this.list.splice(index,1) } } } </script> <style> </style>
<!--子组件--> <template> <li @click="Delete">{{content}}</li> </template> <script> export default { props:['content','index'], methods:{ Delete(){ this.$emit('delete1',this.index) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
//main.js import Vue from 'vue' import Todolist from './Todolist' Vue.config.productionTip = false new Vue({ el: '#app', components: { Todolist }, template: '<Todolist/>' })