vue组件
组件使用的基本步骤
-
使用vue.extend()方法创建组件构造器
-
使用Vue.component()注册组件(全局组件),或者在components方法中定义组件
-
在Vue实例范围内使用组件
全局组件和局部组件
父组件和子组件
//子组件
const cpnC1 = Vue.EXTEND({
template:`
<div>
<h2>我是标题1</h2>
<p>我是内容,哈哈</p>
</div>
`
})
//父组件
const cpnC2 = Vue.EXTEND({
template:`
<div>
<h2>我是标题2</h2>
<p>我是内容,哈哈哈哈</p>
<cpn1></cpn1>
</div>
`
components:{
cpn1:cpnC1
}
})
//爷爷组件
const app = new Vue({
el: "app",
data:{
message:"你好啊"
}
)}
组件的语法糖注册方式
Vue.component('cpn1',{
template:`
<div>
<h2>语法糖注册</h2>
<p>可替代第一步注册组件</p>
<cpn1></cpn1>
</div>
`
})
const app = new Vue({
el: "app",
data:{
message:"你好啊"
},
components:{
'cpn2':{
template:`
<div>
<h2>语法糖注册</h2>
<p>可替代第一步注册组件</p>
<cpn1></cpn1>
</div>
`
}
}
)}
组件模板的分离写法
//1. script标签 ,注意类型必须是text/x-template
<script type="text/x-template" id="cpn1">
<div>
<h2>组件模板分离</h2>
</div>
</script>
// 2. temp标签
<template id="cpn1">
<div>
<h2>组件模板分离方式2</h2>
</div>
</template>
//注册一个全局组件
Vue.component('cpn',{
template:'#cpn1'
})
组件可以访问vue组件
父子组件之间的通信
在用的标签上使用绑定传值
type:表示传值的类型
default:默认值 //在未传值是展示
required:必须传值
props的驼峰标识
不要使用驼峰命名绑定值,html会解析成小写,导致传值失败
父子组件之间通信-子传父
//1 .发射组件
this.$emit()
//2. 再在使用的组件上绑定
//3. 再在父组件的methods中处理