寫一個vue組件
我下面寫的是以.vue結尾的單文件組件的寫法,是基于webpack構建的項目。如果還不知道怎么用webpack構建一個vue的工程的,可以移步到vue-cli。
一個完整的vue組件會包括一下三個部分:
每個組件都有屬于自己的模板,js和樣式。如果將一個頁面比喻成一間房子的話,組件就是房子里的客廳、臥室、廚房、廁所。如果把廚房單獨拿出來的話,組件又可以是刀、油煙機...等等。就是說頁面是由組件構成的,而組件也可以是組件構成的。這樣就可以非常的靈活,耦合性也非常的低。
先來看看一個組件在不是.vue文件內的寫法:
Vue.component('simple-counter', { template: '<div id="inputBox"><input type="text"></div>', data () { // 數據 return { counter: 0 } }, methods: { // 寫點方法 }, created () { // 生命鉤子 }, computed: { // 計算屬性 }})template是用來干嘛的呢?
<template> <div id="inputBox"> <input type="text"> </div></template><!--template就是這個組件的html,也就是下面部分(vue-loader會將template標簽下的內容解析出來):--><div id="inputBox"> <input type="text"></div><!-- 對應原生寫法的話,就是template內的dom字符串-->
js部分
export default { data () { return { counter: 0 } }, methods: { // 方法 }, created () { // 生命鉤子 }, computed: { // 計算屬性 }}// 在這里很明顯js部分就是對應的原生寫法內的非template部分了。// export default這個是es6的模塊寫法,不懂的可以先去了解es6的模塊化css部分
<style lang="scss" scoped>...樣式</style>
<!--這里的你可以使用scss(CSS擴展語言)只要安裝"sass-loader"和"node-sass"這兩個npm包就好了,vue-cli已經配好相關參數了。如果想使用less或其它css擴展語音,只要裝好各自的編譯包就好了。而scoped是讓css的作用域只在該文件下。-->
引入
要怎么在其它組件引用該組件?
組件一(button.vue)
<template> <div class="button"> <button @click="onClick">{{text}}</button> </div></template><script>export default { props: ['text'], // 獲取父組件的傳值 data () { return { } }, methods: { onClick () { console.log('點擊了子組件') } }}</script><style lang="scss" scoped>.button { button { width: 100px; }}</style>組件二(box.vue)
<template> <div class="box"> <v-button :text="text"></v-button> <!--使用組件并傳值(text)--> </div></template><script>import Button from './button.vue' // 引入子組件export default { components: { 'v-button': Button }, data () { return { text: '按鍵的name' } }, methods: { }}</script>
新聞熱點
疑難解答
圖片精選