全局组件写法
<div id="app">
<input type="text" name="name" v-model="inputValue">
<button v-on:click="handleBtnCilck">提交</button>
<button v-on:click="handleBtnClickEmpty">清空</button>
<ul>
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
//全局组件
Vue.component("TodoItem",{
//接收组件传过来的值
props:['content'],
//模版
template:"<li>{{content}}</li>"
})
var vm = new Vue({
el:'#app',
data:{
list:[],
inputValue:''
},
methods:{ //方法
handleBtnCilck: function(){
this.list.push(this.inputValue),
this.inputValue = ''
},
handleBtnClickEmpty: function(){
vm.$data.list = [],
this.inputValue = ''
}
}
})
</script>
定义一个组件叫TodoItem,这是一个全局组件,然后通过list来循环输出多少个组件,同时通过v-bind语法借助content变量传给TodoItem这个子组件,通过props里的content接收父组件传递过来的值并通过模版渲染出来。
局部组件写法
<div id="app">
<input type="text" name="name" v-model="inputValue">
<button v-on:click="handleBtnCilck">提交</button>
<button v-on:click="handleBtnClickEmpty">清空</button>
<ul>
<todo-item v-bind:content="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
//局部组件
var TodoItem = {
props: ['content'],
template:"<li>{{content}}</li>"
}
var vm = new Vue({
el:'#app',
components:{ //通过对象注册局部组件
TodoItem:TodoItem
},
data:{
list:[],
inputValue:''
},
methods:{ //方法
handleBtnCilck: function(){
this.list.push(this.inputValue),
this.inputValue = ''
},
handleBtnClickEmpty: function(){
vm.$data.list = [],
this.inputValue = ''
}
}
})
</script>
局部组件需要在Vue实例中注册局部组件,才可以使用