body>
<div id="app">
<my-component></my-component>
</div>
<script src="lib/vue-2.4.0.js"></script>
<script>
//全局组件
Vue.component('myComponent',{
//1.组件的内容/模板
template: '<div><div>头部组件</div><h1 @click="fn">呵呵{{msg}}</h1></div>',
data(){
return {
msg:'hello,组件'
}
},
methods:{
fn(){
console.log(this.msg);
}
}
})
let vm = new Vue({
el:"#app",
data:{
},
methods:{
},
})
</script>
</body>
局部组件案例
<body>
<div id="app">
<my-component></my-component>
<my-test></my-test>
</div>
<template id="Box1">
<h1>haha</h1>
</template>
<template id="Box2">
<div>
<ul>
<li v-for="item in arr">
{{ item }}
</li>
</ul>
</div>
</template>
<script src="lib/vue-2.4.0.js"></script>
<script>
let vm = new Vue({
el:"#app",
data:{
},
methods:{
},
//局部子组件
components:{
// 组件名: {配置项}
"myComponent":{
template:'#Box1',
data(){
return {
msg:"哈哈"
}
}
},
"myTest":{
template:"#Box2",
data(){
return {
arr:[1,2,3,4]
}
}
}
}
})
</script>
</body>
组件切换:法一
<body>
<div id="app">
<a href="" @click.prevent="flag=true">登录</a>
<a href="" @click.prevent="flag=false">注册</a>
<login v-if="flag"></login>
<register v-else="flag"></register>
</div>
<script src="lib/vue-2.4.0.js"></script>
<script>
Vue.component("login",{
template:"<h1>登录组件</h1>"
})
Vue.component("register",{
template:"<h1>注册组件</h1>"
})
let vm = new Vue({
el:"#app",
data:{
flag: false
---------------------
}
.v-enter-active,
.v-leave-active{
transition: all 0.5s;
position: absolute;
}
</style>
</head>
<body>
<div id="app">
<a href="" :class="{red: flag=='login'}" @click.prevent="flag='login'">登录</a>
<a href="" :class="{red: flag=='register'}" @click.prevent="flag='register'">注册</a>
<!-- vue提供了一个标签 component标签(理解为一个占位符), 用来展示对应名称的组件 :is属性设置指定的组件名 -->
<transition>
<component :is="flag"></component>
</transition>
</div>
<script src="lib/vue-2.4.0.js"></script>
<script>
Vue.component("login",{
template:"<h1>登录组件</h1>"
})
Vue.component("register",{
template:"<h1>注册组件</h1>"
})
let vm = new Vue({
el:"#app",
data:{
flag: "login"
},
methods:{
},
})
</script>
</body>
父组件向子组件传值
<body>
<div id="app">
<my-component :fromfather="father"></my-component>
</div>
<template id="Box1">
<h1 @click="change">
{{ fromfather }}
子组件的数据
</h1>
</template>
<template id="grandSon">
<h1>孙子组件的数据</h1>
</template>
<!--1.子组件不能访问父组件的数据
2. 解决办法: ①在引用子组件时, 通过属性绑定 v-bind方法, 把需要传递给子组件的数据以绑定的形式传过来
② 在子组件配置项里添加 props: ['传递过来的数据']-->
<script src="lib/vue-2.4.0.js"></script>
<script>
let vm = new Vue({
el:"#app",
data:{
father:'啊~~这是父组件的数据'
},
methods:{
},
//局部子组件
components:{
// 组件名: {配置项}
"myComponent":{
template:'#Box1',
data(){
return {
msg:"哈哈"
}
},
//在子组件配置项里添加 props: ['传递过来的数据']
//注意: 组件中所有的props中的数据, 都是通过父组件传递给子组件的, props中的数据是只读, 无法修改
props:['fromfather'],
methods:{
change(){
// this.fromfather = "被修改了"
}
},
//局部子子组件
components:{
'grandSon':{
template:'#grandSon'
}
}
}
}
})
</script>
</body>
---------------------
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。