vue中组件的四种方法总结

时间:2024-01-13 18:29:32

希望对大家有用

全局组件的第一种写法

html:
<div id = "app">
<show></show>
</div>
js:
  第一步:实例化Vue对象
var app = new Vue({
el:"#app"
})
    第二步:定义组件
var myComponent = Vue.extend({
template: '<h1>vue全局组件写法一</h1>'
});
    第三步:注册组件   Vue.component('show',myComponent)
全局组件的第二种写法(注意定义的组件必须在实例化前面)
html:
<div id="app1">
<login></login>
</div>
js:
Vue.component('login',{
template: '<h1>vue全局组件写法二</h1>'
});
var app1 = new Vue({
el:"#app1"
});
全局组件的第三种方法
html:
<template id="recommend">
<h1>这种方法比较推荐</h1>
</template>
<div id="app3">
<recommend></recommend>
</div>
js:
Vue.component('recommend',{
template:'#recommend'
})
var app3 = new Vue({
el:"#app3"
});
全局组件第四种写法(不太推荐)
html    
<script type="x-template" id="recommend1">
<h1>这种方法不太推荐</h1>
</script>
<div id="app4">
<recommend1></recommend1>
</div>
js
Vue.component('recommend1',{
template:'#recommend1'
})
var app13 = new Vue({
el:"#app4"
});