代码
定义局部组件,和模板抽取的两种方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>vueTest</title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="app">
<myheader></myheader>
</div>
<div id="app2">
<myheader></myheader>
</div>
<!--定义模板 方式1-->
<script type="text/x-template" id="mytemp">
<div>
<h3>商品名:{{name}}</h3>
<h3>价格:{{price}}</h3>
<h3>类别:{{goodsType}}</h3>
<h3>描述:{{msg}}</h3>
</div>
</script>
<!--定义模板 方式2-->
<template type="text/x-template" id="mytemp2">
<div>
<h3>商品名:{{name}}</h3>
<h3>价格:{{price}}</h3>
<h3>类别:{{goodsType}}</h3>
<h3>描述:{{msg}}</h3>
</div>
</template>
<script type="text/javascript">
var app=new Vue({
//局部组件p
components:{
"myheader":{
//当含模板有多个标签时,需要有一个根组件把它包起来
//template:"#mytemp",
template:"#mytemp2",
//定义数据
data:function (){
return{
name:"联想小新",
price:12.00,
goodsType:"A类",
msg:"hello"
}
}
}
},
el:"#app",
data:{
goodsType:"A类"
}
});
</script>
</body>
</html>
定义全局组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>vueTest</title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="app">
<myheader></myheader>
</div>
<hr>
<div id="app2">
<myheader></myheader>
</div>
<script type="text/javascript">
//定义全局组件
Vue.component("myheader",{
template:`<div>
<h3>商品名:{{name}}</h3>
<h3>价格:{{price}}</h3>
<h3>类别:{{goodsType}}</h3>
<h3>描述:{{msg}}</h3>
</div>`,
data:function (){
return{
name:"联想小新",
price:12.00,
goodsType:"A类",
msg:"hello"
}
}
});
var app=new Vue({
el:"#app",
});
var app2=new Vue({
el:"#app2",
});
</script>
</body>
</html>