<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定义组件的方式</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<hello></hello>
<my-world></my-world>
<!-- <myWorld></myWorld> -->
</div>
<script>
// 方式1:先创建组件构造器,然后由组件构造器创建组件
// 1. Vue.extend创建组件构造器
var mycom = Vue.extend({
template: '<h2>hello word</h2>'
});
// 2. Vue.component(组件名,组件构造器)
Vue.component('hello', mycom);
// 方式2:直接创建组件 (推荐)
Vue.component('my-world', {
template: '<h2>世界, 你好</h2>'
});
var vm = new Vue({ //这里的vm也是一个组件,称为根组件Root
el: '#app',
data: {
msg: '啦啦啦'
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>组件的分类 全局组件、局部组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="itapp">
<my-hello></my-hello>
<my-world></my-world>
</div>
<div id="app">
{{name}}
<my-hello></my-hello>
<!-- <my-world></my-world> -->
</div>
<script>
// 全局组件 可以在所有的vue实例中使用
Vue.component('my-hello',{
template:'<h2>我是全局组件</h2>',
data(){ //在组件中存储数据时,必须以函数形式,函数返回一个对象
return {
name:'laney'
}
}
});
/**
* 局部组件,只能在当前vue实例中使用
*/
var vm=new Vue({ //这里的vm也是一个组件,称为根组件Root
el:'#itapp',
data:{
msg:'软谋'
},
components:{
'my-world':{
template:'<h2>世界, 你好 {{age}}</h2>',
data(){
return {
age:'20'
}
}
}
}
});
new Vue({ //这里的vm也是一个组件,称为根组件Root
el:'#app',
data:{
name:'tom'
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="flag='my-hello'">显示hello组件</button>
<button @click="flag='my-world'">显示world组件</button>
<!-- 默认每次都会销毁非活动组件并重新创建
缓存,避免重新渲染, -->
<keep-alive>
<component :is="flag"></component>
</keep-alive>
<!-- <my-world></my-world> -->
</div>
<template id="wbs">
<div>
<h3>{{msg}}</h3>
{{time}}
<ul>
<li v-for="(item,index) in arr" :key="index">{{item}}</li>
</ul>
</div>
</template>
<script>
var vm=new Vue({ //这里的vm也是一个组件,称为根组件Root
el:'#app',
data:{
msg:'软谋',
flag:'my-hello'
},
components:{
'my-world':{
name:'wbsx',
template:'#wbs',
data(){
return {
age:'20',
msg:'world',
arr:['tom','jack','laney'],
time:Math.random()
}
}
},
'my-hello':{
template:'<h2>我是my hello {{time}}</h2>',
data(){
return {
time:Math.random()
}
}
}
}
});
</script>
</body>
</html>