使用 Vue.component

引入 vue.js

HTML

<div id="app"></div>

CSS

.greeting {
    padding: 3rem 1.5rem;
    background: pink;
    text-align: center;
    font-family: Georgia, serif;
}

JS

Vue.component('sayHi', {
  template: '<p class="greeting">Hi</p>'
})

new Vue({
  el: '#app',
  template: '<say-hi>'
})

将这些内容写在 index.html 中,打开,可以看见 div#appp.greeting 替换了。

demo 在这里

组件可以不定义为全局的,而是定义成 Vue 实例级别的。

var SayHi = {
  template: '<p class="greeting">Hi</p>'
};

new Vue({
  el: '#app',
  components: {
    // <say-hi> will only be available in parent's template
    'say-hi': SayHi // same as: SayHi: SayHi
  },
  template: '<say-hi>'
})

这份代码,能得到与上面一样的效果,但不是通过使用全局组件实现的。demo 在这里

(完)

原文地址:https://www.cnblogs.com/zhangbao/p/6873149.html