一,看代码
<html>
<head>
<title>Vue.component</title>
</head>
<body>
<div id="app">
<app></app>
</div>
<!-- <span id='baidu'>跳转</span> -->
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
Vue.component("button-counter", {
data: function() {
return {
count: 0
};
},
template:
'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
});
Vue.component("app", {
data: function() {
return {
count: 0
};
},
template:
'<div> <h1>App Component</h1><button @click="insert">click to insert new Component</button> <div id="appId"> </div></div>',
methods: {
insert() {
const component = Vue.component("button-counter");
const instance = new component();
instance.$mount("#appId");
}
}
});
new Vue({
el: "#app"
});
</script>
</body>
</html>
二,分析
1,栗子
<html>
<head>
<title>Vue.component</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
</div>
<!-- <span id='baidu'>跳转</span> -->
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
Vue.component("button-counter", {
data: function() {
return {
count: 0
};
},
template:
'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
});
new Vue({
el: "#app"
});
</script>
</body>
</html>
2,目标控件要放app里面
<div id="app">
<button-counter></button-counter>
</div>
3,需要new一个vue对象
new Vue({
el: "#app"
});
4,创建vue.component主体
Vue.component("button-counter", {
data: function() {
return {
count: 0
};
},
template:
'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
});
5,效果图
三,使用extend
<html>
<head>
<title>Vue.component</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
</div>
<!-- <span id='baidu'>跳转</span> -->
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
var extend = Vue.extend({
data: function() {
return {
count: 0
};
},
template:
'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
});
Vue.component("button-counter", extend);
new Vue({
el: "#app"
});
</script>
</body>
</html>