vue学习——组件
1、组件注册方式
第一种:第一种:使用 Vue.extend 配合 Vue.component 方法(一般不建议在js语句写大量的html标签):
// 定义组件第一种方法
//extend没有s。不是extends
var login=Vue.extend({template:`<button>component1</button>`})
Vue.component('com1',login)
第一种的合并写法:
Vue.component('com2',{
template:`<button>component2</button>`
})
组件模板分离写法:有两种标签可以用 ,一个是script标签,一个是template标签:
- script标签的使用:即用script标签包裹建立的组件内容,注意必须注明script的类型
<script type="text/x-template" id="temp1">
<button >component3</button>
</script>
//在 <script type="text/javascript" >中注册定义temp1
Vue.component("com3",{template:"#temp1"})
- 用template标签:相比script标签使用比较方便,直接在body范围中写
<template id="temp2">
<div>
<button >component4</button>
</div>
</template>
//在 <script type="text/javascript" >中注册定义temp2
Vue.component("com4",{template:"#temp2"})
父子组件:
子组件的创建,在父组件的component中创建components:
Vue.component("com1", {
template: "#temp1",
data() {
return {
isshow: true,
fmsg: "这里是父组件/全局组件",
msgf: "这是父组件的信息",
msgArr: [111, 222, 333]
}
},
//创建子组件是用components,注意有s!!!
components: {
"com2": {
template: "#temp2",
},
}
})
父组件传递数据给子组件:利用props属性。
- 先在子组件中添加props(注意子组件有两种形式,一是字符串数组,二是对象,对象形式可以限定数据类型以及一些默认值)
//数组类型如下:
// props: ['msgf','arr'],
//对象类型如下
props:{
msgf:{
//数据类型
type:String,
//default为默认值,当没人传值过来的时候使用默认值
default:'我只是一个默认值',
//当require为true的时候代表必须给他传值,否则报错!
required:false,
},
arr:{
type:Array,
//当数据类型为数组时,不能直接用【】,否则报错
// default:[]无效默认值
// 当默认类型是对象或者数组时必须要是一个函数!~~~
default:function(){
return [4,5,6]
}
}
- 在父组件的模板处,即父组件调用子组件的位置将子组件的props属性赋值
<template id="temp1">
<div>
<button @click="isshow=!isshow">这里是全局/父组件</button>
<p v-if="isshow">{{fmsg}}</p>
<div class="clr"></div>
<!-- 传递父组件的信息用props后需要在最顶层进行属性的绑定! -->
<com2 :msgf="msgf" :arr="msgArr"></com2>
</div>
</template>
注意:目前暂时不是很支持驼峰写法,对于props的变量最好都用小写,用-代替驼峰的大写比较好一点比如myArr=》my-arr,只有v-bind可以将驼峰改成 - 的写法.v-on也不能用驼峰法用驼峰写好像会报错或者发出警告。
子组件向父组件传递信息:使用this.$emit()方法
- 在子组件的方法中调用this.$emit()方法,设置事件名以及需要传递的数据
2.在父组件调用子组件的时候将子组件创建的事件名与父组件的事件相互绑定(注意:绑定的时候不需要写上形参,会默认将传递的数据当作唯一一个参数)
//父组件
<template id="temp1">
<div>
<button @click="isshow=!isshow">这里是全局/父组件</button>
<p v-if="isshow">{{fmsg}}</p>
<p v-if="isSon">{{sonMsg.id}}---{{sonMsg.name}}</p>
<div class="clr"></div>
//在这里将子组件发送数据的事件名和父组件指定的事件绑定
<com2 @son-msg="show"></com2>
</div>
</template>
子组件
<template id="temp2">
<div>
<p>这里是子组件</p>
//在button添加点击事件,利用$emit方法传递数据给父组件
<button v-for="(item,index) in msg" @click="send(item)">{{item.name}}</button>
</div>
</template>
//子组件添加$emit方法
methods: {
send(item){
this.$emit("son-msg",item);
console.log("子组件发送成功")
}
}
//父组件事件接受show,默认第一个参数是子组件传递的数值
methods: {
//默认传进一个值
show(data) {
console.log(data);
this.isSon = true
this.sonMsg = data;
}
},