Vue.extend
template传入自定义组件的模板
//创建构造器
const cpn1 = Vue.extend({
template:`
组件1
A
`
})
全局组件/局部组件/父子组件
//全局注册
Vue.component("cpn",cpn1})
//局部注册在实例中 组件内部也可以注册另一个组件
const app = new Vue({
el:'#app',
components:{
cpn:cpn1
}
})
//父子组件 在组件内注册另一个组件就可以在父组件中使用子组件
const cpnF = Vue.extend({
template:`
父组件
A
`,
components:{
cpnS:cpnS
}
})
//注册组件的语法糖 直接在实例中注册
const app = new Vue({
el:'#app',
components:{
cpn2:{
template:`
组件2语法糖
可以直接使用
`
}
}
})
组件模板抽离script template 标签写法
<script type="text/x-template" id="cpn">
<div>
<h2>我是cpn from script</h2>
<p>{
{
title}}</p>
</div>
</script>
<template id="cpn">
<div>
<h2>我是cpn from template</h2>
<p>{
{
title}}</p>
</div>
</template>
//需要根据id进行注册
Vue.component("cpn",{
template:`#cpn`
})
组件模板内数据 data以及methods
组件的数据单独存放在对象内 并且是个函数
思考为什么需要是个函数?
组件也有自己单独的方法不能使用Vue实例中的
//js
Vue.component("cpn",{
template:`#cpn`,
data(){
return {
count:0
}
},
methods:{
Add(){
this.count++
},
Sub(){
this.count==0?console.log("不能再减小啦"):this.count--
}
}
})
//html
<div id="app">
<cpn></cpn>
</div>
<template id="cpn">
<div>我是计数器:{
{
count}}
<button @click="Add">+</button>
<button @click="Sub">-</button>
</div>
</template>
父传子:通过props(properties)从父组件接受数据
<div id="app">
<cpn :cfruit="fruit" :cmessage="message"></cpn>
</div>
<template id="cpn">
<p>{
{
cfruit}}</p>
<p>{
{
cmessage}}</p>
</template>
//js
const cpn={
template:`#cpn`,
props:['cfruit','cmessage']
}
const app = new Vue({
//父组件
el:'#app',
data:{
fruit:['梨子','芒果','牛油果','草莓'],
message:'ch'
},
components:{
cpn
}
})
const cpn={
template:`#cpn`,
props:{
//类型限制
cfruit:{
type:Array,
default(){
return[]
}
},
cmessage:{
//默认值
type:String, //类型限制
default:'aaa', //默认值
required:false //必须传值
}
}
}
<div id="app">
//监听自定义事件 写到父组件methods中
<cpn @item-click="cpnClick"></cpn>
</div>
<template id="cpnC1">
<div>
<button v-for="item in categories"
@click="btnClick(item)">//写在组件内部methods
{
{
item.name}}
</button>
</div>
</template>
const cpn={
template:'#cpnC1',
data(){
return{
categories:[
{
id:'aaa',name:'梨子'},
{
id:'bbb',name:'芒果'},
{
id:'ccc',name:'牛油果'},
{
id:'ddd',name:'草莓'}
]
}
},
methods:{
btnClick(item){
//发射到父组件
this.$emit('item-click',item)
}
}
}
const app = new Vue({
el:'#app',
data:{
},
components:{
cpn
},methods:{
cpnClick(item){
//获得数据输出
console.log(item.name)
}
}
})