本文分享一個簡單的Vue.js組件示例,示範如何定義一個帶有雙向綁定、自定義屬性與事件的組件,並在父組件中調用它。
先看組件本身(componentExample.vue):
<template>
<div class='content' v-if='showFlag'>
<input type="text" v-bind:style='{ width: compwidth + "px" }'
v-model='compvalue' @keyup='myFun' v-el:getvalue>
<label class='example-label'>觀察參數"compvalue"的變化:</label>{{compvalue}}
<button class='btn btn-danger' @click='compfun'>確定</button>
</div>
</template>
<script>
export default {
// 從父組件接收資料
props: {
compvalue: {
type: String, // 型別(String, Number, Boolean, Function, Object, Array)
required: true, // 是否必填
twoWay: true, // 指定雙向綁定
default: '' // 預設值
},
compwidth: {
coerce: function (val) {
return val + ''; // 將值轉為字串
}
},
compfun: {
type: Function,
required: true
}
},
ready: function() {},
computed: {}, // 計算屬性
methods: { // 組件自身的方法
myFun: function(){
alert(this.$els.getvalue.value);
}
},
data() { // 綁定資料
return {
showFlag: true
};
}
}
</script>
父組件調用(App.vue):
<template>
<div class='example-content'>
<compexample :compvalue.sync='values' :compfun='compFun'></compexample>
</div>
</template>
<script>
import compexample from './componentExample.vue' // 引入組件
export default {
components: { compexample },
ready: function() {},
methods: {
compFun: function(){
alert('喵嘞個咪');
}
},
data() {
return {
values: 'hello'
};
}
}
</script>
在組件中,透過 props 從父組件接收資料(並可指定型別、是否必填、雙向綁定與預設值),透過 methods 定義組件自身的行為,並用 components 在父組件裡註冊後即可使用。組件代碼中我已為大部分屬性加上註釋,方便理解。
調用後的效果如下:
