创建组件
使用Vue.extend创建
<div id="app">
<my-com1></my-com1>
</div>
<script>
var com1=Vue.extend({
template:"<h3>这是一个用Vue.extend创建的组件</h3>"//组件要展示的具体内容
})
Vue.component("myCom1",com1);//定义组件的名称
var Vue = new Vue({
el: "#app",
data: {
},
methods: {
}
})
</script>
注意这里是因为驼峰式才会这样
可以合成一步:
Vue.component("myCom1",Vue.extend({
template:"<h3>这是一个用Vue.extend创建的组件</h3>"//组件要展示的具体内容
}));
但是这样写字符串比较麻烦,所以看方式三:
<div id="app">
<my-com1></my-com1>
</div>
<template id="temp">
<div>
<p>来来来</p>
<h3>Vue is very good</h3>
</div>
</template>
<script>
Vue.component("myCom1",Vue.extend({
template:"#temp"//组件要展示的具体内容
}));
var Vue = new Vue({
el: "#app",
data: {
},
methods: {
}
})
</script>
同样我们可以定义一下私有的组件:
var Vue = new Vue({
el: "#app",
data: {
},
methods: {
},
components:{
myCom1:{
template:"#temp"
}
}
})
这样也能达到一样的效果
父组件向子组件传值
<div id="app">
<com v-bind:parentmsg="msg"></com>
</div>
<script>
var vm=new Vue({
el:'#app',
data:{
msg:'父组件中的值'
},
methods:{
},
components:{
com:{
template:'<h1>这是子组件---{{ parentmsg }}</h1>',
props:['parentmsg']
}
}
})
</script>
利用props进行参数传递,并且props里面的数据是可读但是不可写的
父组件向子组件传递函数
<body>
<div id="app">
<mycom1 @func="show"></mycom1>
</div>
<template id="tmp">
<div>
<h1>这是子组件</h1>
<input type="button" value="触发" @click="myclick">
</div>
</template>
<script>
var mycom1 = {
template: '#tmp',
data(){
return {
sonmsg:15
}
},
methods:{
myclick(){
this.$emit('func',this.sonmsg)
}
}
}
// Vue.component("mycom1",Vue.extend({
// template:"#temp"
// }))
var vm = new Vue({
el: '#app',
data: {
msg: '父组件中的值'
},
methods: {
show(da) {
console.log("调用了父组件的方法----"+da)
}
},
components: {
mycom1
}
})
</script>
</body>
vm是父组件,mycom1是子组件,注意$emit方法,用来父组件的函数。