vue组件定义,全局、局部组件,配合模板及动态组件功能示例

2020-06-13 10:36:18易采站长站整理

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script>
<style>
</style>
</head>
<body>
<div id="box">
<my-aaa></my-aaa>
</div>
<script type="x-template" id="aaa">
<h2 @click="change">标题2->{{msg}}</h2>
<ul>
<li>1111</li>
<li>222</li>
<li>3333</li>
<li>1111</li>
</ul>
</script>
<script>
var vm=new Vue({
el:'#box',
components:{
'my-aaa':{
data(){
return {
msg:'welcome vue'
}
},
methods:{
change(){
this.msg='changed';
}
},
template:'#aaa'
}
}
});
</script>
</body>
</html>

方法二:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script>
<style>
</style>
</head>
<body>
<div id="box">
<my-aaa></my-aaa>
</div>
<template id="aaa">
<h1 @click="change">{{msg}}</h1>
<ul>
<li v-for="val in arr">
{{val}}
</li>
</ul>
</template>
<script>
var vm=new Vue({
el:'#box',
components:{
'my-aaa':{
data(){
return {
msg:'welcome vue',
arr:['apple','banana','orange'] }
},
methods:{
change(){
this.msg='changed title';
}
},
template:'#aaa'
}
}
});
</script>
</body>
</html>

三、动态组件

动态组件:


<component :is="组件名称"></component>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script>
<style>
</style>
</head>
<body>
<div id="box">
<input type="button" @click="a='aaa'" value="aaa组件">
<input type="button" @click="a='bbb'" value="bbb组件">
<component :is="a"></component>