寫在前言:
組件:是可複用的 Vue 實例。
在註冊一個組件的時候,我們始終需要給它一個名字,該組件名就是 Vue.component
的第一個參數。
組件命規則:
1、使用 kebab-case
Vue.component('my-component-name', { /* ... */ })
當使用 kebab-case (短橫線分隔命名) 定義一個組件時,你也必須在引用這個自定義元素時使用 kebab-case,
例如 <my-component-name>
。
2、使用 PascalCase
Vue.component('MyComponentName', { /* ... */ })
當使用 PascalCase (首字母大寫命名) 定義一個組件時,你在引用這個自定義元素時兩種命名法都可以使用。也就是說 <my-component-name>
和 <MyComponentName>
都是可接受的。注意,儘管如此,直接在 DOM (即非字符串的模板) 中使用時只有 kebab-case 是有效的。
註冊全局組件1:main.js
// 定義一個名爲 button-counter 的全局新組件
Vue.component('button-counter', {
data () {
return {
count: 0
}
},
template: '<button class="button" v-on:click="onClick">You clicked me {{ count }} times.</button>',
methods: {
onClick() {
console.log('觸發事件')
this.count++
}
}
})
或寫法2:main.js
import Children from '@/components/children.vue'
Vue.component('button-counter', Children)
children.vue
<template>
<div>
<button class="button" v-on:click="onClick">You clicked me {{ count }} times.</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
onClick() {
console.log('觸發事件')
this.count++
}
}
}
</script>
使用相同:
<button-counter></button-counter>
局部註冊組件:
import ComponentA from './ComponentA.vue'
export default {
components: {
ComponentA
},
// ...
}