1 两种组件注册方式
1.1 全局注册
- 定义的时候用驼峰命名,使用的时候用短横线
- 使用的时候用属性传值,定义的时候用props接收值
- 传值的时候使用的是横线间隔,接受的时候使用驼峰
- 传值时(不区分大小写)使用驼峰命名,接受的时候使用全小写
代码示例如下:
首先是HTML代码:
<div id="app">
<t-button></t-button>
</div>
然后是JS代码
<script src="../vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
// 注册全局组件
Vue.component('tButton',{
data: function(){
return {
count: 0
}
},
template: '<button type="button" v-on:click="count++"> You have hited me {{ count }} times</button>'
})
new Vue({
el: '#app'
})
</script>
1.2 局部注册
代码示例如下:
<div id="app">
<hello-world></hello-world>
</div>
<script src="../vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var helloWorld = {
template:'<div>王大锤</div>'
}
let vm = new Vue({
el:'#app',
components:{
'helloWorld': helloWorld
}
});
</script>
2 组件间的两种传值方式
2.1 父传子,props
父组件中,将数据以属性的方式绑定在子组件上,子组件通过props取出
代码示例如下:
首先是父组件:
<template>
<div id="father">
<h3>父组件</h3>
<son :counts="student"></son>
</div>
</template>
<script>
import Son from "./Son";
export default {
name: "Father",
components: {Son},
data() {
return {
student: [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
},{
id: 3,
name: 'c'
},
]
}
}
}
</script>
<style scoped>
</style>
然后是子组件
<template>
<div id="son">
<h3>子组件</h3>
<table border="1">
<tr>
<th>id</th>
<th>name</th>
</tr>
<tr v-for="count of counts">
<th>{{ count.id }}</th>
<th>{{ count.name }}</th>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "Son",
props:[
'counts'
]
}
</script>
<style scoped>
</style>
2.2 子传父,$emit()
子组件通过this.$emit(methodName,message)方法向父组件派发一个函数,值为message,
父组件中,给子组件绑定事件@methodName=“getMessage”,然后,在methods中定义方法getMessage(event){},这里的参数event就是传递过来的值
父组件代码如下:
<template>
<div id="father">
<h3>父组件</h3>
<son @sendMsg="getMsg"></son>
<p>
父组件接收到的值是:{{ getM }}
</p>
</div>
</template>
<script>
import Son from './Son'
export default {
name: "Father",
components: {Son},
data(){
return {
getM: ''
}
},
methods:{
getMsg(event){
this.getM=event;
}
}
}
</script>
<style scoped>
</style>
子组件代码如下:
<template>
<div id="son">
<h3>子组件</h3>
<p>
子组件要传递的值是:{{ message }}
</p>
<button type="submit" @click="sendMessage">发送</button>
</div>
</template>
<script>
export default {
name: "Son",
data(){
return {
message: 'This is Son'
}
},
methods:{
sendMessage(){
this.$emit('sendMsg',this.message);
}
}
}
</script>
<style scoped>
</style>